【问题标题】:Number of Rows in UITableView Needs to Differ after Delete删除后 UITableView 中的行数需要不同
【发布时间】:2014-08-01 02:35:17
【问题描述】:

我有一个包含多个部分的表格。当给定部分没有行时,我从numerOfRowInSection 返回 1,然后创建一些默认文本。我不允许选择或编辑此行。

问题在于,此部分确实允许在有数据时删除行(我再次在没有数据时禁用此功能并且我正在显示我的默认文本)。但是,假设本节中有一行实际数据。当用户删除此行时,它应该重新加载表格并显示我的默认文本,因为此部分不再存在数据。实际发生的是应用程序终止错误,因为在删除之后它需要 0 行(1 行之前,1 行删除,0 行结果)。在我的代码中,虽然当 rows 为 0 时,我返回 1,所以数学不起作用并且错误会关闭所有内容。

问题:如何在表格为空但允许删除时保留默认行,以便在删除最后一行数据时允许我的 1 个默认文本而不是预期的没有行?

删除代码:

         - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
        {
            if (editingStyle == UITableViewCellEditingStyleDelete)
            {
                [self deleteFav:indexPath.row];
                [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
    }

处理行数和默认值的代码:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) return [self.channelIDArray count];
    else if (section == 1)
        if ([self.favChannelIDArray count]>0) return [self.favChannelIDArray count];
        else return 1;
}

错误:

2014-07-31 19:47:19.194 ephIM[3183:60b] * 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无效更新:第 1 节中的行数无效. 更新后现有节中包含的行数 (1) 必须等于更新前该节中包含的行数 (1),加上或减去从该节中插入或删除的行数 (0已插入,1 已删除)并加上或减去移入或移出该部分的行数(0 移入,0 移出)。'

【问题讨论】:

  • 显示处理删除的代码。
  • 另外,请出示您的错误日志。
  • 我将两者都添加到我的 OP 中。谢谢。

标签: objective-c uitableview ios7


【解决方案1】:

当没有正常行时,您的代码没有考虑您的额外行。您需要添加:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        [self deleteFav:indexPath.row];
        [tableView beginUpdates];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        if (indexPath.section == 1 && self.favChannelIDArray.count == 0) {
            // This tells the table to insert the "dummy" row you want
            [tableView insertRowsAtIndexPaths:@[ [NSIndexPath indexPathForRow:0 inSection:indexPath.section] ] withRowAnimation:UITableViewRowAnimationFade];
        }
        [tableView endUpdates];
    }
}

【讨论】:

  • 谢谢!这让我朝着正确的方向前进,因为我没有意识到你不能简单地重新加载表数据和这个阶段。请注意,“initForRow”似乎无效。这是我使用的: [tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
  • 我修正了索引路径的错字。您可以在此阶段简单地重新加载表格,但是当您只需要添加/删除一行时,调用 reloadData 有点矫枉过正。
  • 我同意,我不是在调用重新加载数据。我的想法是这将是删除记录后的方法。但是,这并不像前面提到的那样工作。您的回答当然是正确的方法。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多