UITableView 繼承自 UIScrollView,是 Apple 封裝好的捲動列表元件。上面排列著一個個 UITableViewCell,每個 cell 可以回應點擊事件,也可以塞入 UITextField、UITextView 等子檢視來支援編輯。
列表可能有數百甚至上千筆資料,若每次都配置新的 cell,記憶體很快就會不夠用。因此 UIKit 為每個 cell 指定一個重用識別符(reuseIdentifier)代表「這一類 cell」,當 cell 捲出螢幕時會被放進重用佇列;下次需要顯示同類型的 cell 時,就從佇列中取出來重複使用。
對於結構單純的 cell,這套機制運作良好。但遇到「同一個識別符下混用了多種不同結構的 cell」時就會出錯。
舉例來說:某個含有 UITextField 子檢視的 cell 被放進了重用佇列,接著一個「不該有任何子檢視」的位置需要顯示 cell,系統從佇列中取出剛才那個,於是文字輸入框就憑空出現在不該有它的地方。這類 bug 的典型症狀是「捲動時內容隨機錯位、殘留」。
把取得 cell 的方法從 dequeueReusableCellWithIdentifier: 換成 cellForRowAtIndexPath:。
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
// 改為以下寫法
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// ...其他設定程式碼
return cell;
}
原理是:重用機制呼叫的就是 dequeueReusableCellWithIdentifier:,顧名思義是「從佇列中取出一個可重用的 cell」。改用 cellForRowAtIndexPath: 則是精確地針對該 indexPath 取得 cell,完全不動用重用佇列。
但要誠實說明這個做法的代價:在 iOS 6 之後,cellForRowAtIndexPath: 若找不到對應的可見 cell 會回傳 nil,這代表你放棄了重用帶來的效能優勢。資料量大時捲動會明顯變卡,因此這比較適合「cell 數量本就很少」或「快速止血」的情境,不建議作為長期方案。
重用機制只會在同一個識別符之間重用,識別符不同的 cell 不會互相混用。因此只要讓每一列的識別符都不同,就能徹底避免錯亂。
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 以 indexPath 唯一確定識別符
NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d%d",
[indexPath section], [indexPath row]];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// ...其他設定程式碼
return cell;
}
這個做法保留了 cell 存在的意義(捲出後再捲回來時不必重新配置),但代價是記憶體會隨資料量線性成長,因為每一列都會各自保留一份。資料筆數固定且不多的情況下是可行的折衷。
這個思路是「把髒掉的 cell 洗乾淨再交給下一位使用者」。
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
else
{
// 刪除 cell 的所有子檢視
while ([cell.contentView.subviews lastObject] != nil)
{
[[cell.contentView.subviews lastObject] removeFromSuperview];
}
}
// ...其他設定程式碼
return cell;
}
這個做法保留了完整的重用效能,記憶體占用也最穩定,是我最推薦的止血方式。要注意的是它必須搭配「每次都在 cellForRow 中重新建立所有子檢視」的寫法,否則清掉之後就沒有東西可顯示了。
上述三種都是在「同一個識別符塞多種 cell」的前提下補救。其實問題的根源是設計上的:不同結構的 cell 本來就該用不同識別符。
正確做法是為每一種 cell 樣式定義各自的識別符,例如 @"textCell"、@"imageCell"、@"inputCell",在 cellForRow 中依型別分別 dequeue。這樣既能享有完整的重用效能,也不會有內容錯亂的問題。
另外兩個搭配使用的好習慣:一是在自訂 cell 中覆寫 prepareForReuse,把上一輪殘留的狀態(文字、圖片、勾選框)重置;二是把 cell 的設定邏輯集中在 configureWithModel: 這類方法中,確保每次 dequeue 後都完整覆寫所有可變屬性——「忘記重設某個屬性」是這類 bug 最常見的成因。