UITableView 繼承自 UIScrollView,是蘋果封裝的一個基於滾動的強大控件。它由一個個 UITableViewCell 組成,每個 cell 都能響應點擊事件,還可以在其中添加 UITextField、UITextView 等子視圖進行文字編輯。
列表中的 cell 數量可能非常多,為了節省內存,系統引入了「重用」機制:為每個 cell 指定一個重用標識符(reuseIdentifier),當 cell 滾出屏幕時會被放入重用隊列;當有新的 cell 需要顯示時,就從隊列中取出舊 cell 重複使用。
然而,對於結構多變的自定義 cell,這種重用機制偶爾會出錯。舉個例子:一個含有 UITextField 子類的 cell 被放進重用隊列後,如果接下來要顯示的是一個本不包含任何子視圖的 cell,系統卻取出了那個帶子視圖的 cell 來顯示,內容自然就錯亂了。
把取 cell 的方法從 dequeueReusableCellWithIdentifier: 換成 cellForRowAtIndexPath:。後者只從指定行精確取出 cell,不走重用隊列,問題便可避免,代價是可能犧牲一些內存:
- (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;
}
重用機制依據相同的標識符來複用 cell,標識符不同的 cell 無法彼此重用。因此,只要讓每個 cell 的標識符都不一樣,就能從根本上杜絕錯亂:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)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) {
[(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
}
}
// ...其他代碼
return cell;
}
也可以簡潔地用一行代碼實現清空:
// 刪除 cell 的所有子視圖 [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
三種方法各有取捨:方法一簡單但費內存,方法二精準但需要管理眾多標識符,方法三則在保留重用機制的同時主動清理。實際開發中,可根據 cell 結構的複雜程度靈活選擇,或結合使用。