如何删除表格视图中的单元格

有人可以build议我的代码是什么问题…..

self.modleClass.foldersAray有一个对象,tableview有一个部分和一个行

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source [self.tableview setEditing:YES animated:YES]; [self.modleClass.foldersAray removeObjectAtIndex:indexPath.row]; [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YEs]; [tableView reloadData]; } } 

我得到如下错误。

 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).' 

像这样做,

 -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { [self.modleClass.foldersAray removeObjectAtIndex:indexPath.row]; [tableView reloadData]; } } 

这是更多………

如果你的tableView是基于foldersAray ,那么从这个数组中删除一个对象并重新加载tableview将导致删除这个单元格。 你可以删除该行:

 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YEs]; 

如果你想animation试试这个,如果你不想animation使用@Mountain狮子的答案。

  -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { [self.modleClass.foldersAray removeObjectAtIndex:indexPath.row]; [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]withRowAnimation:UITableViewRowAnimationFade]; } } 

如果你有导航编辑button,你应该打电话

[self.tableView setEditing:YES animated:YES];

在你的方法里面开始编辑。

如果你需要的内存对你无关紧要,那么你可以通过将高度设置为0来显着地删除(隐藏)单元格。

 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row%2) { return 0; } return 100; } 

PS:上面的虚拟代码会显着删除备用单元。

这个错误意味着,你必须更新你的数据源(数组,数据,字典或任何你使用的)

例如:删除前有5个单元,dataArray中有5个对象。 在调用deleteRowsAtIndexPaths:之前,我们必须从dataArray中移除与此单元相关联的对象,然后才调用deleteRowsAtIndexPaths: 也可以使用[tableView reloadData]使用

 [tableView beginUpdates]; [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; [tableView endUpdates]; 

PS我看到,你从数据源中删除对象,所以仔细检查,也许你错过了什么