【发布时间】:2013-01-11 15:04:38
【问题描述】:
我有一个带有 1 部分的简单 UITableView,其中存在任意数量的带有 UITextFields 的自定义 UITableViewCells(KMInputCell 类型)的行。当用户开始在最后一个(空白)文本字段中输入时,会插入一个新的空白行(因此用户可以创建一个类似列表的结构)。由于我只会在视图关闭时“保存”数据,因此数据源只是一个 NSUInteger 跟踪行数。
在用户从表中删除一行之前,我的代码可以正常工作。然后,当用户开始在列表末尾键入并应插入新(空白)行时,插入的 UITableView 单元格包含已删除单元格中的旧数据。更糟糕的是,当多行被删除,然后用户开始输入(并且应该插入一个空白行)时,多行被删除的行会突然出现。
这是在编辑单元格中的一个 UITextField 时调用的 fieldChanged: 方法(其中self.last_cell 返回该部分中的最后一个单元格):
- (IBAction)fieldChanged:(id)sender {
// get the text field of the last row
// if it has a value that is not blank, insert another row
KMInputCell* last_cell = self.last_cell;
if(![last_cell.textField.text isEqualToString:@""]){
[self.tableView beginUpdates];
NSIndexPath* new_cell_path = [NSIndexPath indexPathForItem:[self.tableView numberOfRowsInSection:0] inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:new_cell_path] withRowAnimation:UITableViewRowAnimationAutomatic];
number_emails++;
[self.tableView endUpdates];
}
}
这是用于删除单元格的commitEditingStyle: 方法:
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
number_emails--;
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
加法
这里是cellForRowAtIndexPath::
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"add_email_prototype";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];=
// Configure the cell...
return cell;
}
【问题讨论】:
-
如果您的“数据源”只是一个 int,那么您将“稍后保存”的文本存储在哪里?这绝对不是表格视图所期望的那种数据源。你能展示你的
cellForRowAtIndexPath委托方法吗? -
我会把
cellForRowAtIndexPath放在上面。我没有在数据源中提供数据的原因是数据仅由用户在单元格的 UITextFields 中提供。 -
正如艾萨克所说,你需要清除单元格;在 Isaac 发表评论的地方插入代码。此外,您绝对应该考虑使用某种数据模型。你的方法会失败。
-
正如我在他的回答中评论的那样,由于用户管理 UITextFields 中的数据,如果删除单元格,这不会使事情变得复杂吗?那么是不是很难弄清楚要删除哪个数组元素等?
-
这并不复杂 - 只需查看表格视图数据源和委托的文档即可。
标签: iphone ios objective-c uitableview