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

iOS 開發實戰:解決 UITableView Cell 重用導致內容出錯的三種方法

編輯:iOS 開發綜合

UITableView 繼承自 UIScrollView,是蘋果封裝好的滾動控件,上面排列著一個個的 UITableViewCell。Cell 可以響應點擊事件,也能加入 UITextField、UITextView 等子視圖進行文字編輯。

一、重用機制的原理與問題

為了節省內存,UITableView 通常會重用 cell:透過為每個 cell 指定一個 reuseIdentifier(重用標識符)來標示它的種類。當 cell 滾出螢幕時會被放進重用佇列,等到有新的 cell 要顯示時,就從佇列中取出來重用。

但對於多變的自定義 cell,這種機制有時會出錯。舉例來說,當一個含有 UITextField 子視圖的 cell 被放進重用佇列後,如果此時一個「不含任何子視圖」的 cell 要顯示,系統就會把這個帶有子視圖的 cell 取出重用,導致內容錯亂。

二、解法一:改用 cellForRowAtIndexPath:

把取得 cell 的方法從 dequeueReusableCellWithIdentifier: 換成 cellForRowAtIndexPath:。後者只從指定行精準取出 cell,而不走重用佇列,因此可避免出錯,代價是可能多耗費一些內存。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    // 改為根據 indexPath 精準取出一行,而非從重用佇列取出
    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
{
    // 以 indexPath 唯一確定 cell
    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 的所有子視圖

這個方法在 reuse 時,把 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 結構單純的情況。可依實際需求挑選。

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