您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

UITableView Cell 重用導致內容錯亂的三種修復思路

編輯:iOS 開發綜合

問題從哪裡來

UITableView 是 Apple 在 UIScrollView 基礎上封裝出來的高性能列表控件,畫面上排列著一個又一個 UITableViewCell。每個 cell 都可以響應點擊,也可以塞進 UITextField、UITextView 這類子視圖,直接在行內完成文字編輯。

列表裡的 cell 數量可能成千上萬,全部真實創建會迅速吃光內存,因此系統引入了「重用」機制:每個 cell 都帶有一個 reuseIdentifier 標識其類型,當某個 cell 滾出屏幕,它並不會被銷毀,而是被放進一個待重用佇列;等到有新的行需要顯示,就從佇列裡取出一個舊 cell 反覆使用。

問題恰恰出在這裡。當自定義 cell 的樣式差異很大時,重用機制會「張冠李戴」。舉例來說,一個帶有 UITextField 子類的 cell 被放回了重用佇列,而接下來需要顯示的卻是一個完全沒有子視圖的樸素行,系統仍會把這個帶輸入框的 cell 取出來交差,界面上於是出現了不該存在的輸入框、圖片或按鈕。

方案一:繞開重用佇列

把取 cell 的方法從 dequeueReusableCellWithIdentifier: 換成 cellForRowAtIndexPath:。前者顧名思義是「出列一個可重用的 cell」,後者則是按 indexPath 精確取出指定行,天然不會與佇列裡的舊對象混淆。代價是失去了內存複用的好處,行數多時開銷明顯,只適合小列表。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    // 註解掉原來的重用方式
    // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    // ...其餘配置代碼
    return cell;
}

方案二:讓每一行擁有專屬標識符

重用機制只會在標識符相同的 cell 之間發生,標識符不同就無法互相污染。因此可以用 section 與 row 拼出一個唯一 key,讓每行各自維護自己的複用池。

- (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 徹底洗乾淨,讓它回到「白紙」狀態,再按當前行重新搭建內容。

- (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 {
        // 移除 contentView 上的全部子視圖
        while ([cell.contentView.subviews lastObject] != nil) {
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    // ...其餘配置代碼
    return cell;
}

更值得推薦的工程做法

上述三種方案都屬於「事後補救」。在真實項目中,更穩健的寫法是為不同樣式設計不同的 cell 類與不同的 reuseIdentifier,並在每次出列後對 cell 的每一個可變狀態顯式賦值——包括文字、圖片、選中態、隱藏與否。只要養成「不做 if 判斷、無條件覆蓋」的習慣,內容錯亂的問題基本不會再出現。

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