用 UITableView 顯示成千上萬筆資料時,為什麼從不卡頓?答案藏在它的「Cell 重用機制」裡。理解這個機制,你才能寫出高效、不出錯的列表。本文先剖析重用原理,再整理一份實戰中反覆用到的 TableView 常用程式碼。
當你建立 UITableViewController 子類時,IDE 生成的程式碼裡有這麼一段:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = [NSString stringWithFormat:@"Cell"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// 設定 cell
return cell;
}
為了做到顯示與資料分離,iOS 的 tableView 並不是為每個資料項都建立一個 cell,而是只建立「螢幕可顯示的最大個數」的 cell,然後重複使用它們,再對每個 cell 做單獨的顯示配置。這樣既不影響顯示效果,又能充分節約記憶體。
查看 UITableView 標頭檔,會找到 visibleCells(保存當前顯示的 cells)與 reusableTableCells(保存可重用的 cells)兩個結構。
TableView 剛顯示時,reusableTableCells 為空,所以 dequeueReusableCellWithIdentifier: 回傳 nil,初始的 cell 全靠 alloc 建立。以 100 筆資料、一屏最多顯示 10 個 cell 為例:
alloc 建立 10 次 cell,指定相同的重用標識,全部加入 visibleCells,reusableTableCells 為空。visibleCells,cell1 移出並加入 reusableTableCells。reusableTableCells 已有值,dequeueReusableCellWithIdentifier: 回傳 cell1;cell1 重新加入 visibleCells,cell2 移出並加入可重用表。之後新的 cell 就能正常重用了。正因如此,配置 cell 時一定要對取出的重用 cell 重新賦值,別遺留舊資料!這是新手最常踩的坑——圖片錯亂、文字重疊,往往就是忘了重設。
並非只有拖動超出螢幕才會更新 reusableTableCells,還有:
一、建立 UITableView
DataTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 420)];
[DataTable setDelegate:self];
[DataTable setDataSource:self];
[self.view addSubview:DataTable];
[DataTable release];
二、各 Method 說明
// 右側索引標題
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return TitleData;
}
// 每個 section 的標題
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return @"";
}
// 指定分區數量,預設 1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 4;
}
// 每個分區的行數,預設 1
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 0;
}
// 繪製 Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:SimpleTableIdentifier] autorelease];
}
cell.imageView.image = image; // 未選時的圖片
cell.imageView.highlightedImage = highlightImage; // 選中後的圖片
return cell;
}
// 行縮進
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
return [indexPath row];
}
// 改變行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 40;
}
// 選中 Cell 的響應事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
// 阻止選中第一行
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([indexPath row] == 0) return nil;
return indexPath;
}
// 滑動時是否出現刪除按鈕
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
// 提交編輯(刪除等)
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
// 在這裡處理刪除資料
}
三、在 Cell 上建立多行 UILabel
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
UILabel *Datalabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 320, 44)];
[Datalabel setTag:100];
Datalabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:Datalabel];
[Datalabel release];
}
UILabel *Datalabel = (UILabel *)[cell.contentView viewWithTag:100];
[Datalabel setFont:[UIFont boldSystemFontOfSize:18]];
Datalabel.text = [data.DataArray objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
最後附上幾個常用列舉:選中樣式 UITableViewCellSelectionStyle(None/Blue/Gray)、右側按鈕樣式 UITableViewCellAccessoryType(None/DisclosureIndicator/DetailDisclosureButton/Checkmark)、分隔線樣式 UITableViewCellSeparatorStyle(None/SingleLine),以及用 tableView.separatorColor 改變分隔線顏色。把這些碼錟收好,日後做列表就能得心應手。