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

标签 objective-c ios

我正在尝试为我的应用实现自定义删除流程,因为我的客户不想要表格 View 编辑模式提供的红色圆圈。我为每一行添加了一个删除按钮,其标记属性中有行号。一旦用户点击删除按钮,它会触发以下方法:

-(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).'

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

非常感谢。

最佳答案

您正试图删除一行,而您的数据源仍反射(reflect)原始状态(即删除前的状态)。您必须首先更新数据源,只有这样您才能从表 viev 中删除。您也不需要将按钮设置为nil,也不需要在 TableView 上调用-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];
}

(但是,您应该做的一件事是注意您的代码格式。)

关于objective-c - 无法以编程方式从 UITableView 中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13324102/

相关文章:

ios - 如何将多个对象保存到关系实体中。 Xcode

objective-c - 使用 Shift 键扩展 NSCollectionView 中的选择

iphone - 如何使用 Xcode 制作首次启动 iPhone App 的导览

android - 后台发短信到自己的手机号,短信列表不显示已发短信

ios - iBeacons 对 iOS 10.x 中框架的更改

iphone - 在特定时间向 iPhone 发送当前位置

ios - Xcode 使用未解析的标识符错误

ios - IOS 7.0 中 CFStream Socket 发送数据包不完整

ios - 选择行时,UITableView 数据排序返回错误数据

ios - 在 Swift 中检测摇动手势 SpriteKit