无法以编程方式从UITableView中删除行

the*_*men 2 objective-c ios

我正在尝试为我的应用程序实现自定义删除过程,因为我的客户不想要由表视图编辑模式提供的红色圆圈.我为每一行添加了一个删除按钮,其标签属性中包含行号.用户点击删除按钮后,会触发以下方法:

-(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;


}
Run Code Online (Sandbox Code Playgroud)

我总是得到这个错误:

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).'
Run Code Online (Sandbox Code Playgroud)

所以我不知道我在这段代码中是否遗漏了什么.

非常感谢.

小智 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];
}
Run Code Online (Sandbox Code Playgroud)

(但是,您应该做的一件事是关注如何格式化代码.)