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

iOS 修正 UITableViewCellAccessoryCheckmark 顯示錯亂的問題

編輯:iOS 開發綜合

在 UITableView 上做多選時,常會遇到一個惱人的現象:勾選的勾勾會跑到別的 cell 上,或者捲動之後勾選狀態全亂。這不是 iOS 的 bug,而是 cell 重用機制被誤用了。


問題根源:dequeueReusableCell 會重用 cell


先看建立 cell 的標準寫法:


UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                  reuseIdentifier:cellStr];
}

關鍵在於:dequeueReusableCellWithIdentifier: 拿到的很可能不是一個全新的 cell,而是剛剛捲出畫面的那一個。如果你只在「點擊時」設定 accessoryType,卻沒有在「每次配置 cell 時」重設它,那麼被重用的 cell 就會帶著上一筆資料的勾勾出場——這就是錯亂的來源。


解法一:把選中狀態記在資料層


先建立一個 NSMutableArray 來記錄被選中的項目,命名為 selectedData。然後在單擊事件裡維護它:


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *str = cell.textLabel.text;
    NSDictionary *dict = [self getOneDictByName:str];

    if ([self isExistsByName:str theArray:selectedData]) {
        [self removeOneFromArrayByName:str theArray:selectedData];
    } else {
        [selectedData addObject:dict];
    }

    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                    withRowAnimation:UITableViewRowAnimationAutomatic];
}

這裡的 selectedData 是一個 NSMutableArray。點擊時不是去改 cell 的樣子,而是去改「資料」——已選就移除,未選就加入,然後只重繪那一列。


解法二:在 cellForRowAtIndexPath 每次都重設 accessoryType


-(UITableViewCell*)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellStr = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:cellStr];
    }

    NSArray *keys  = [tempResult allKeys];
    NSArray *dicts = [tempResult valueForKey:[keys objectAtIndex:indexPath.section]];
    NSDictionary *temp = [dicts objectAtIndex:indexPath.row];
    cell.textLabel.text = [temp valueForKey:@"name"];

    if ([selectedData containsObject:temp]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}

這裡有個細節千萬不能省:if 與 else 必須兩個都寫完整。很多人只寫了 if 分支設定 checkmark,卻忘了在 else 分支設回 None,結果就是重用 cell 上的勾勾永遠不會消失。只要每次配置 cell 都把 accessoryType 明確設成兩種狀態之一,重用帶來的髒狀態就會被強制覆蓋掉。


背後的設計思路:MVC


這個問題真正的解法其實不是那個 if-else,而是觀念上的轉換:視圖只用來呈現,究竟要顯示什麼,取決於 model。


當你把「哪些項目被選中」這個事實存在 selectedData 這個 model 裡,view 就退化成一張純粹的畫布——每次重繪時老實地問 model「這筆選了沒」,然後照著畫。這樣一來,cell 被重用多少次、順序怎麼變、畫面怎麼捲,都不再有任何影響。


反過來,如果把選中狀態存在 cell 物件上,那狀態就跟著 cell 一起被回收再利用,錯亂無可避免。這也是為什麼 UITableView 的所有可變狀態(勾選、展開、文字內容)都應該由 dataSource 持有,而不是由 cell 自己記著。

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