您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS TableView Cell 重用機制解析與常用程式碼大全

編輯:iOS 相關資訊

用 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 為例:

  1. 最開始用 alloc 建立 10 次 cell,指定相同的重用標識,全部加入 visibleCells,reusableTableCells 為空。
  2. 向下拖動,當 cell1 完全移出螢幕、cell11 完全顯示時,cell11 加入 visibleCells,cell1 移出並加入 reusableTableCells。
  3. 繼續向下拖,因為 reusableTableCells 已有值,dequeueReusableCellWithIdentifier: 回傳 cell1;cell1 重新加入 visibleCells,cell2 移出並加入可重用表。之後新的 cell 就能正常重用了。

正因如此,配置 cell 時一定要對取出的重用 cell 重新賦值,別遺留舊資料!這是新手最常踩的坑——圖片錯亂、文字重疊,往往就是忘了重設。

幾種特殊情況

並非只有拖動超出螢幕才會更新 reusableTableCells,還有:

  • reloadData:一般是在部分資料變化、需要刷新顯示時呼叫。此時 cellForRowAtIndexPath 中所有 cell 都是重用的(推測 reloadData 後會把 visibleCells 全部移入 reusableTableCells 並清空)。
  • reloadRowsAtIndex:刷新指定的 IndexPath。若呼叫時 reusableTableCells 為空,則建立新 cell;舊 cell 移出後加入可重用表,之後的刷新就有 cell 可重用。

TableView 常用程式碼

一、建立 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 改變分隔線顏色。把這些碼錟收好,日後做列表就能得心應手。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved