如何在tableview中同时插入更多行?

时间:2012-03-21 04:50:07

标签: ios iphone xcode

我想同时在tableview的最后一行前面插入很多行,但是它在最后一行前面加了一行,最后又加了两行。怎么搞清楚?请帮帮我,谢谢你。 !

- (void)morePicture:(id)sender{
    NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
    for (int i=0; i<3; i++) {
        NSString *s = [[NSString alloc] initWithFormat:@"%d",i];
        [photos addObject:s];
        NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i inSection:0];
        [indexPaths addObject:indexpath];
   }

   [table beginUpdates];
   [table insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
   [table endUpdates];

   [table reloadData];
}

enter image description here

3 个答案:

答案 0 :(得分:3)

- (void)morePicture:(id)sender {
    // See how many rows there are already:
    NSUInteger rowCount = [table numberOfRowsInSection:0]
    NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
    for (int i=0; i<3; i++) {
        NSString *s = [[NSString alloc] initWithFormat:@"%d",i];
        [photos addObject:s];
        // The new index path is the original number of rows plus i - 1 to leave the last row where it is. 
        NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i+rowCount - 1 inSection:0];
        [indexPaths addObject:indexpath];
    }

    [table beginUpdates];
    [table insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
    [table endUpdates];

    [table reloadData];
}

答案 1 :(得分:2)

我不确定我的确切含义是什么,但您不应该在[table reloadData]之后致电[table endUpdates]

答案 2 :(得分:0)

我认为你遇到的麻烦可能来自于在数组的最后一行之前添加行的想法。每次添加时,最后一行都会更改。如果你可以正确地获得索引,那么只需在indexPaths中使用这些索引,它就会全部解决,我想:

NSInteger insertPosition = photos.count - 1;  // this index will insert just before the last element
for (int i=0; i<3; i++) {
    NSString *s = [[NSString alloc] initWithFormat:@"%d",insertPosition];  // not i
    [photos insertObject:s atIndex:insertPosition];
    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:insertPosition inSection:0];
    [indexPaths addObject:indexpath];
    insertPosition++;  // advance it, because the end of the table just advanced
}

[table beginUpdates];
[table insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
[table endUpdates];
// no need to reload data as @sampage points out