我尝试设法从UITable
中删除UIViewController
中的一行。我使用导航栏中的Edit
按钮。点击它会将表格行置于编辑模式。但是当按下一行中的删除按钮时,使用以下内容时出现错误...'Invalid update: invalid number of rows in section 0….
:
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
[self.tableView setEditing:editing animated:YES];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSMutableArray *work_array = [NSMutableArray arrayWithArray:self.inputValues];
[work_array removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
我在这里想念什么? Apple文档似乎已经过时了。 感谢
答案 0 :(得分:2)
问题很简单。在从表中删除行之前,您没有正确更新数据模型。
您所做的就是创建一些新数组并从中删除一行。那毫无意义。您需要更新其他数据源方法使用的相同数组,例如numberOfRowsInSection:
。
答案 1 :(得分:1)
您遇到的问题是您没有直接更新表的数据源。你首先根据你的数据源创建一个名为work_array的全新数组(我假设它是self.inputValues),然后你从中删除一个项目,然后尝试删除一行,但你的tableView的数据源仍然包含该项目你打算删除。
您需要做的就是确保self.inputValues是一个可变数组并直接删除该数组索引处的对象,如下所示:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.inputValues removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
我希望有所帮助!