【问题标题】:insert/create new row in a same section of uitableview在 uitableview 的同一部分插入/创建新行
【发布时间】:2011-07-09 06:37:44
【问题描述】:

我遇到了一个问题,我有一个带有行的 uitableview,比如说 5。 如果用户选择了一行,那么应该在被点击的行下方创建/插入一个新行,并带有动画(正如我们在部分隐藏/取消隐藏中看到的那样),并且在点击新插入的行时应该将其删除。

我试过了,但它说

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 (6) must be equal to the number of rows contained in that section before the update (5), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted).'

那么实现此功能的其他方法应该是什么? 提前致谢。

【问题讨论】:

    标签: iphone uitableview insert row nsindexpath


    【解决方案1】:

    最初您有 5 行。您向表中添加一个新行,假设使用 addRowsAtIndexPaths: 方法。此时,您的表格视图将调用其数据源方法,因为它需要添加这个新单元格。

    但是,您的数据源方法可能仍然返回 5 行(而不是 6 行),这导致不一致(因为表格视图需要 6 行,而您仍然返回 5 行)

    因此,假设当表格视图为新创建的单元格(行 = 5)调用 cellForRowAtIndexPath: 方法时,它可能会崩溃,因为您必须执行以下操作:

    [yourDatasourceArray objectAtIndex:indexPath.row];
    

    上述语句会导致崩溃,因为 indexPath.row 为 5,而您的数组中仍有 5 个对象(索引 0 到 4)。因此 objectAtIndex:5 会导致崩溃。

    【讨论】:

    • 这很可能是答案。总之,在您调用insertdelete 之后,从numberOfRows 返回正确的号码。
    • 大家好...感谢cmets...我已经解决了问题...请在下面找到我的答案
    【解决方案2】:
    - (NSInteger)numberOfRowsInSection:(NSInteger)section { switch (section) { case 0: return numberOfRows; } return 0; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { numberOfRows ++; [tableView deselectRowAtIndexPath:indexPath animated:NO]; NSMutableArray* tempArray = [[NSMutableArray alloc] init]; [tempArray addObject:[NSIndexPath indexPathForRow:indexPath.row +1 inSection:indexPath.section]]; [tableView beginUpdates]; [tableView insertRowsAtIndexPaths:tempArray withRowAnimation:UITableViewRowAnimationRight]; [tableView endUpdates]; [tempArray release]; }

    我犯了两个错误 1) 更新后我没有使用 [tableView beginUpdates] 并且显然 [tableView endUpdates] 2) 计算 newRow 的 indexpath 的方法不明确。

    非常感谢 pratikshabhisikar 和 Max Howell 投入时间和精力。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多