在UITableView中動態的插入或刪除行(或者節)


http://blog.iosxcode4.com/archives/105

在UITableView中插入或者刪除指定的行(或者節)使用的是如下幾個API:

  • insertRowsAtIndexPath: withRowAnimation: 在指定位置插入行
  • deleteRowsAtIndexPath: withRowAnimation: 刪除指定行
  • insertSections: withRowAnimation: 在指定位置插入節
  • deleteSections: withRowAnimation: 刪除指定節

調用以上API之前,必須先調用beginUpdates,插入/刪除數據完成后再調用endUpdates。

-(IBAction)addRows:(id)sender{

NSMutableArray *indexPaths = [[NSMutableArray alloc] init];

for (int i=0; i<3; i++) {

NSString *s = [[NSString alloc] initWithFormat:@”hello %d”,i];

[datas addObject:s];

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];

[indexPaths addObject: indexPath];

}

[self.tableView beginUpdates];

[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewScrollPositionNone];

[self.tableView endUpdates];

}

-(IBAction)delRows:(id)sender{

NSMutableArray *indexPaths = [[NSMutableArray alloc] init];

[datas removeObjectAtIndex:0];

[indexPaths addObject:[NSIndexPath indexPathForRow:0 inSection:0]];

[self.tableView beginUpdates];

[self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];

[self.tableView endUpdates];

}

需要注意的是,調用insert函數時,需保證數據源添加的記錄數要與你想插入的行的總數一致,如上面的例子中,想要插入的記錄有3條,插入位置分 別為1,2,3,則對應的indexpPaths數組的元素總數為3,數組元素為一個NSIndexPath對象,通過它我們指定了記錄的插入位置。刪除 數據也是相同的道理。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM