ios - 如何删除tableView单元iOS

标签 ios objective-c uitableview

我是 Objective-C 的新手。所以我有一个表格 View ,该部分中有 5 行(5 个单元格),我想允许用户删除它们,但是当我单击删除按钮时应用程序不断崩溃。它崩溃的原因是因为我在该部分中有 5 行而不是返回 [self.myListItems count] 如何在保留该部分中的 5 行的同时更正下面的代码?

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source


        [self.myListItems removeObjectAtIndex:indexPath.row];
        [self saveList];

        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

错误是:-[UITableView _endCellAnimationsWithContext:] 中的断言失败

最佳答案

在 ViewDidLoad 中:

self.tableView.allowsMultipleSelectionDuringEditing = NO;


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //add code here for when you hit delete
        [self.myListItems removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self saveList];
    }    
}

请记住 - 如果您想删除一个部分中的最后一项,则需要删除整个部分(否则可能会导致部分计数错误并引发此异常)。

希望这可以帮助。

关于ios - 如何删除tableView单元iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38238262/

相关文章:

ios - 如何查找最近两个月未访问的文件列表?

iphone - 如何确定 View Controller

ios - swift ; scrollView 搭配 tableView 可行吗?

ios - 自定义 UISwitch 兼容所有版本的 iOS

ios - 在设备上运行但不在 Swift 模拟器中运行时的断点

ios - UITableViewCell 内的自定义绘图 UIView

objective-c - 查看方法调用的返回值

ios - 将 scrollOffset 保存到 didEndDisplayingCell 中的 UITableView 数据源未正确出列

ios - iOS8 中的多行/动态 UILabel 截断

ios - 如何使用 swift 在 Storyboard中从一个 View Controller 移动到另一个 View Controller