【发布时间】:2015-10-17 20:22:03
【问题描述】:
我有一个 UITableView,它允许用户将行动态添加到表中。 UITableView 最初从 0 行开始。每一行都是一个自定义的 UITableViewCell,它包含两个单独的 UITextField:一个包含文本,一个包含数字。 UITableView 有一个可见区域,显示 4 行,然后随着每个新行的添加而滚动。每当用户添加新行时,我会在 NSMutableDictionary 中的 UITableView 中添加先前添加的行中的值,其中键是名称字段的值,值是数字字段的值。
我成功地将行添加到 UITableView,并成功地将数据存储到我的 NSMutableDictionary 中。然而我的问题是,添加行后,如果用户决定向上或向下滚动 UITableView,突然之间,用户输入的表格行中的数据完全关闭。
这是我正在谈论的内容的屏幕截图:
它应该是什么样子:
当我滚动到顶部时的样子:
这是我正在使用的相关代码:
- (IBAction)addChoice:(id)sender {
if ([self.tableData count] > 0) {
NSString *name = [[(MyCustomCell *)[self.choiceTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:[self.tableData count]-1 inSection:0]] nameField] text];
NSString *number = [[(MyCustomCell *)[self.choiceTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:[self.tableData count]-1 inSection:0]] priceField] text];
if (name && price) {
[self.tableDictionary setObject:number forKey:name];
}
}
NSString *theObjectToInsert = [NSString stringWithFormat:@"Row #: %lu", (unsigned long)[self.tableData count]];
[self.tableData addObject:theObjectToInsert];
NSIndexPath *newPath=[NSIndexPath indexPathForRow:self.tableData.count-1 inSection:0];
[self.choiceTable insertRowsAtIndexPaths:@[newPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.choiceTable scrollToRowAtIndexPath:newPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
[[(MyCustomCell *)[self.choiceTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:[self.tableData count]-1 inSection:0]] nameField] becomeFirstResponder];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCustomCell *cell = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if ([self.tableDictionary count] > 0) {
NSArray *keys = [self.tableDictionary allKeys];
if ([indexPath row] == 0) {
cell.nameField.text = keys[indexPath.row];
cell.numberField.text = self.tableDictionary[keys[indexPath.row]];
} else if ([indexPath row] <= ([self.tableDictionary count]-1)) {
cell.nameField.text = keys[indexPath.row-1];
cell.numberField.text = self.tableDictionary[keys[indexPath.row-1]];
} else {//if the row was just added by the user, display a table with empty fields
cell.nameField.text = @"";
cell.numberField.text = @"";
}
}
[cell.contentView setBackgroundColor:[UIColor colorWithRed:0.89 green:0.36 blue:0.01 alpha:1.0]];
return cell;
}
谁能看出我做错了什么?
【问题讨论】:
-
如果您将
keys记录在tableView:cellForRowAtIndexPath:中,您是否始终拥有所需顺序的数据?因为allKeys订单没有定义。
标签: ios objective-c uitableview