1. 程式人生 > >在UITableView中動態的插入或刪除行(或者節)

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

在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物件,通過它我們指定了記錄的插入位置。刪除 資料也是相同的道理。