0

我遇到了一个问题,我有一个带有行的 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).'

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

4

2 回答 2

2

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

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

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

[yourDatasourceArray objectAtIndex:indexPath.row];

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

于 2011-07-09T07:00:12.950 回答
0

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

}



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

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

于 2011-07-10T09:32:23.473 回答