UITableView 是 iOS 列表類需求的核心元件。本文從基本結構一路談到重用機制與自訂 Cell,把最常打交道的 API 整理成一份可反查的筆記。
預設有兩種風格:
UITableViewStylePlain:不分組UITableViewStyleGrouped:分組UITableView 只有「行」的概念,沒有「列」,每一行就是一個 UITableViewCell。系統內建的 cell 樣式有四種:
typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
UITableViewCellStyleDefault, // 左側 textLabel,imageView 可選(最左)
UITableViewCellStyleValue1, // 左 textLabel、右 detailTextLabel(預設藍色)
UITableViewCellStyleValue2, // 左側依次顯示 textLabel(藍色)與 detailTextLabel
UITableViewCellStyleSubtitle // 左上 textLabel、左下 detailTextLabel(預設灰色)
};
#pragma mark 常用資料源方法 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; // 分組數 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; // 每組行數 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; // 每行的 cell - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section; // 組標題 - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section; // 組尾說明
呼叫順序是:計算分組數 → 計算每組行數 → 產生索引 → 產生 cell。要注意 cellForRowAtIndexPath: 只會為目前畫面上看得見的行產生 cell。
#pragma mark - 常用代理方法 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section; // 組頭高度 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; // 行高(可各不同) - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section; // 組尾高度 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath; // 點擊某行 - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section; // 自訂組頭視圖 - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section; // 自訂組尾視圖
- (void)reloadData; // 刷新整個表格
- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths
withRowAnimation:(UITableViewRowAnimation)animation; // 刷新指定行
- (void)reloadSections:(NSIndexSet *)sections
withRowAnimation:(UITableViewRowAnimation)animation; // 刷新指定分組
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths
withRowAnimation:(UITableViewRowAnimation)animation; // 刪除行
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths
withRowAnimation:(UITableViewRowAnimation)animation; // 新增行
UITableView 內部有一個重用池。它不是一次建立全部 cell,而是「所見即所得」——只有畫面上看得見的行才有對應的 cell 實例。
因此即使資料量龐大,記憶體中同時存在的 cell 數量仍然有限,大幅降低記憶體壓力。
#pragma mark 在 tableView:cellForRowAtIndexPath: 中使用重用機制
// 此方法的呼叫頻率非常高,identifier 宣告為靜態變數有助於效能
static NSString *cellIdentifier = @"UITableViewCellIdentifierKey1";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
}

實務上很少直接用系統樣式,彈性實在太有限,多數情況都會自訂。
initWithStyle:reuseIdentifier:,在其中加入子控件。layoutSubviews 設定子控件的 frame。tableView:cellForRowAtIndexPath: 中透過重用機制取得該 cell,並設定資料。

實務上建議把 cell 的資料綁定邏輯封裝在 cell 內部(例如自訂 model setter),控制器只負責「把 model 交給 cell」,這樣程式碼會乾淨很多,也更容易測試。