實作 commitEditingStyle 即可啟用刪除模式。點擊 Delete 時,先從資料來源移除物件,再呼叫 deleteRowsAtIndexPaths 更新畫面。
[self.books removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic];
若要改按鈕文字,可實作 titleForDeleteConfirmationButtonForRowAtIndexPath。
若希望先出現紅色減號,再左滑顯示刪除,可將 tableView.editing 設為 YES。
大量資料若每次建立新 cell 會耗效能。iOS 提供 dequeueReusableCellWithIdentifier,讓離開畫面的 cell 進入重用池。
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = @"hello";
return cell;
也可在 viewDidLoad 註冊 class 或 nib,再由系統自動建立與重用。若使用 Storyboard Prototype Cell,則不需手動註冊。