开发者

insert/create new row in a same section of uitableview

I am stuck in a problem, I have a uitableview with rows let say 5. If a user selects one row then a new row exactly beneath the tapped row should be created/inserted with an animation (as we have seen with sections hiding/unhiding) and upon tap of the newly inserted row it should be deleted.

I have given a try but it says


Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid  
update: invalid number of ro开发者_如何学编程ws 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).'

so what should be the other way to achieve this functionality ? Thanks in advance.


Initially you have 5 rows. You add a new row to the table, lets say using addRowsAtIndexPaths: method. At this point, your table view will call its datasource methods, as it needs to add this new cell.

But, probably your still returning number of rows as 5 (and not 6), from your datasource methods, which resulted in inconsistency (as table view expects 6 rows and you are still returning 5 rows)

So, lets say when the table view calls cellForRowAtIndexPath: method for the newly created cell (row = 5), it could crash because you must be doing something as:

[yourDatasourceArray objectAtIndex:indexPath.row];

The above statement would result in crash, as indexPath.row is 5 and your array still has 5 objects in it (index 0 to 4). Thus objectAtIndex:5 results in crash.



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

}



I was making 2 mistakes 1) I wasnot using [tableView beginUpdates] and obviously [tableView endUpdates] after updation 2) The method to calculate the indexpath for a newRow was ambigious.

Thankyou very much pratikshabhisikar and Max Howell for putting your time and efforts in.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜