【问题标题】:how to delete tableView cell iOS如何删除tableView单元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?
  • 在“deleteRowsAtIndexPaths”方法之后,您需要重新加载表格视图。

标签: ios objective-c uitableview


【解决方案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];
      

      【讨论】:

        猜你喜欢
        • 2016-01-21
        • 2016-12-25
        • 1970-01-01
        • 1970-01-01
        • 2017-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多