我正在尝试为我的应用实施自定义删除过程,因为我的客户不想要表视图版本模式提供的红色圆圈。我为每一行添加了一个删除按钮,其标签属性中包含行号。用户点击删除按钮后,会触发以下方法:
-(IBAction)deleteRow:(id)sender{
UIButton *tempButton = (UIButton*)sender;
[self updateTotals];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tempButton.tag inSection:0];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView reloadData];
[sharedCompra removeItem:tempButton.tag];
tempButton=nil;
}
我总是得到这个错误:
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 (3) must be equal to the number of rows contained in that section before the update (3), 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).'
所以我不知道我在这段代码中是否遗漏了什么。
非常感谢。
答案 0 :(得分:12)
您尝试删除一行,而您的数据源仍然反映原始状态(即删除前的状态)。您必须先更新数据源 ,然后才能从表格viev中发出删除。您也不需要将按钮设置为nil
,也不需要在表格视图上调用- reloadData
:
- (void)deleteRow:(id)sender
{
UIButton *tempButton = sender;
[self updateTotals];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tempButton.tag inSection:0];
[sharedCompra removeItem:tempButton.tag];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
(但是,您应该做的一件事是关注您如何格式化代码。)
答案 1 :(得分:1)
在[sharedCompra removeItem:tempButton.tag];
和[tableView deleteRowsAtIndexPaths...
[tableView reloadData]
问题在于,当您致电deleteRowsAtIndexPath:
时,它正在调用numberOfRowsInSection
,它会从您的模型中返回相同的计数。
此处不需要reloadData
来电。
答案 2 :(得分:0)
删除和添加行时,需要调用beginUpdates,这里应该看起来如何。
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];
并且您不需要调用reloadData,否则它将取消deleteRows和insertRows方法的动画。但是你确实需要重置数据,所以如果你正在使用NSMutableArray,你需要首先删除对象,所以在索引0处的项目,然后你可以删除表中的第0行。行数在结束删除时需要与该数组中的对象数相匹配,否则也会崩溃。