您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS UITableView 左滑刪除與 Cell 重用

編輯:iOS 開發綜合

左滑刪除

實作 commitEditingStyle 即可啟用刪除模式。點擊 Delete 時,先從資料來源移除物件,再呼叫 deleteRowsAtIndexPaths 更新畫面。

[self.books removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:@[indexPath]
                      withRowAnimation:UITableViewRowAnimationAutomatic];

若要改按鈕文字,可實作 titleForDeleteConfirmationButtonForRowAtIndexPath。

若希望先出現紅色減號,再左滑顯示刪除,可將 tableView.editing 設為 YES。

Cell 重用

大量資料若每次建立新 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,則不需手動註冊。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved