2012-03-21 64 views
0

我想同時在tableview中的最後一行前面插入很多行,但它在最後一行前面加上一行,並在末尾加上兩行。如何弄清楚?請幫助我,提前謝謝你。 !如何在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
- (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]; 
} 
+0

Inafziger,謝謝爲了您的幫助,但我不想在表格末尾添加行,我只想在最後一行之前添加行 – AlvinZhu 2012-03-21 15:23:56

+0

好吧,只需在創建indexPath時使用rowCount - 1即可。 – lnafziger 2012-03-21 15:50:29

+0

你能幫我解決以下問題嗎?http://stackoverflow.com/questions/11246562/adding-dynamic-sub-rows-by-selecting-tableview-row-in-tableview-iphone-errors/11246768#11246768 – 2012-07-11 14:07:26

2

不知道我得到什麼你的意思,但你不應該需要調用[table reloadData][table endUpdates]

+0

sampage,感謝您的回答,但它不工作 – AlvinZhu 2012-03-21 15:26:23

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 
+0

謝謝,但它不起作用 – AlvinZhu 2012-03-21 15:25:43