UITableView 是 iOS 最常被使用的元件之一,但它的相關 API 分散在 data source 與 delegate 兩組協定中,初學時容易搞混。以下依主題整理最關鍵的幾塊。
無分組的表格只需實作兩個方法:
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return self.contacts.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 1. 建立(或複用)cell
MJContactCell *cell = [MJContactCell cellWithTableView:tableView];
// 2. 綁定模型資料
cell.contact = self.contacts[indexPath.row];
return cell;
}
若表格有分組,還需實作 -numberOfSectionsInTableView:,並用 indexPath.section 與 indexPath.row 兩個維度定位資料。
全量刷新
[self.tableView reloadData];
局部刷新(前提:刷新前後的資料筆數不變)
- (void)reloadRows:(NSArray *)indexPaths
withRowAnimation:(UITableViewRowAnimation)animation;
局部刪除(前提:刪除的筆數必須等於 indexPaths 的長度)
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths
withRowAnimation:(UITableViewRowAnimation)animation;
局部插入
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths
withRowAnimation:(UITableViewRowAnimation)animation;
這些方法的共同鐵律是:呼叫之前必須先改模型資料,呼叫之後資料源的回傳值必須與畫面一致。若模型改了 3 筆卻只呼叫 2 個 indexPaths,UITableView 內部的一致性檢查會直接拋出例外。
只要實作了下面這個方法,就自動獲得「左滑顯示刪除鈕」的能力。使用者按下刪除鈕後,系統會呼叫它,你需要在其中判斷是刪除還是插入:
#pragma mark - UITableViewDelegate
/**
* 實作了這個方法,就自動具備滑動刪除功能
* 使用者按下刪除鈕後會呼叫
* 提交一個編輯操作(刪除/插入)時會呼叫
*
* @param editingStyle 編輯行為
* @param indexPath 操作的列號
*/
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// 1. 先改模型資料
[self.contacts removeObjectAtIndex:indexPath.row];
// 2. 再刷新畫面(局部刪除)
[self.tableView deleteRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationTop];
// 3. 持久化
[NSKeyedArchiver archiveRootObject:self.contacts toFile:MJContactsFilepath];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// 1. 插入模型資料
MJContact *contact = [[MJContact alloc] init];
contact.name = @"jack";
contact.phone = @"10086";
[self.contacts insertObject:contact atIndex:indexPath.row + 1];
// 2. 局部插入對應的列
NSIndexPath *nextPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[nextPath]
withRowAnimation:UITableViewRowAnimationBottom];
}
}
// 切換 tableView 的編輯狀態
[self.tableView setEditing:!self.tableView.isEditing animated:YES];
實作 -editingStyleForRowAtIndexPath: 後,進入編輯狀態時系統會對每一列詢問該做什麼操作:
/**
* tableView 進入編輯狀態時呼叫,詢問每一列進行怎樣的操作(插入/刪除/無)
*/
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return indexPath.row % 2 ? UITableViewCellEditingStyleDelete
: UITableViewCellEditingStyleInsert;
}
cell 沒有複用。範例中每次都用 cellWithTableView: 建立新 cell,若為自訂寫法請確認內部有走 dequeue 流程。標準做法永遠是 dequeueReusableCellWithIdentifier:,否則長列表會嚴重卡頓並耗盡記憶體。
動畫常數不一致。刪除模型用 UITableViewRowAnimationTop、插入用 Bottom 只是視覺選擇,但要確保同一批操作中的動畫方向連貫,否則看起來會很跳。
持久化時機。每次刪除都存檔在大量資料時成本很高。實務上可以標記「有未存變更」,在 viewWillDisappear: 或收到記憶體警告時再一次寫入。
archiveRootObject 已被取代。NSKeyedArchiver 的這類便利方法在後續版本被標記為不建議使用,請改用 archivedDataWithRootObject:requiringSecureCoding:error:,或直接採用 NSCoding 搭配 NSFileManager。更現代的選擇是 Core Data、SwiftData 或 GRDB 等資料層方案。
批量更新要用 performBatchUpdates。若一次要進行多筆插入與刪除,包在 performBatchUpdates:completion: 中可避免多次重排造成的閃爍與狀態不一致。
iOS 13 之後的 UIContextMenu。左滑操作只是其中一種;若需要預覽與多動作選單,可改用 UICollectionView 搭配 contextMenuConfigurationForItemAtPoint:,或直接實作 UIContextMenuInteraction。