如何删除tableView单元iOS

Posted

技术标签:

【中文标题】如何删除tableView单元iOS【英文标题】:how to delete tableView cell iOS 【发布时间】:2016-11-09 08:19:04 【问题描述】:

我是 Objective-C 的新手。所以我有一个表格视图,该部分中有 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];
    

错误是:Assertion failure in -[UITableView _endCellAnimationsWithContext:]

【问题讨论】:

删除单元格后是否重​​新加载了TableView?顺便说一句,为什么即使删除一个单元格也要保留 5 行,这应该会减少行数? 你的意思是你在numberOfRowsInSection返回静态5? ***.com/questions/10134841/… 在“deleteRowsAtIndexPaths”方法之后,您需要重新加载表格视图。 【参考方案1】:

在 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];
        

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

希望这会有所帮助。

【讨论】:

【参考方案2】:

更改以下几行

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

 if (editingStyle == UITableViewCellEditingStyleDelete) 
 // Delete the row from the data source
 [tableView beginUpdates]
 [self.myListItems removeObjectAtIndex:indexPath.row];
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 [tableView endUpdate];
 [self saveList];

【讨论】:

【参考方案3】:

尝试使用这些:

[self.myListItems removeObjectAtIndex:indexPath.row];

[tableView beginUpdate];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];

[self saveList];

【讨论】:

以上是关于如何删除tableView单元iOS的主要内容,如果未能解决你的问题,请参考以下文章

对于这种边缘情况,如何检测何时从 iOS 的 uitableview 中删除单元格?

无法从swift ios中的一段tableview中删除单元格

如何保持 Tableview 滚动以及如何在 Swift3 中删除原型单元和 tableview 之间的空白空间

如何从 tableview 的单元格中删除 imageView,并重置单元格的高度

通过点击 iOS 中的红色减号图标来删除 tableview 单元格

如何通过单击单元格中的按钮来删除 tableView 中的单元格?使用核心数据