iOS 从视图控制器中的表中删除行



我尝试设法从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];
    }
}

我在这里错过了什么?苹果文档似乎以某种方式过时了。谢谢

问题很简单。在从表中删除行之前,您未正确更新数据模型。

您要做的就是创建一些新数组并从中删除一行。这毫无意义。您需要更新其他数据源方法(如 numberOfRowsInSection: )使用的相同数组。

您遇到的问题是没有直接更新表的数据源。您首先基于数据源创建一个名为 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];
    }
}

我希望这有所帮助!

最新更新