您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

UITableView 加上搜尋功能時,cell 為 nil 判斷不可省略

編輯:iOS 技巧大全

在自訂的表視圖上加入搜尋欄,是常見需求。本文記錄實作時踩到的一個關鍵細節:搜尋結果與一般列表共用同一個 Reuse Identifier 時,那段「cell 是否為 nil」的判斷絕對不能拿掉。

為什麼這個判斷很重要

在搜尋模式下,如果仍然用自訂 cell 的 style 去建立物件,或是把 nil 判斷整段移除,就會出現「找不到對應 identifier 的 cell」而報錯的情況。原因是搜尋結果用的是系統預設的 UITableViewCellStyleSubtitle,與原本自訂的 cell style 不同。

關鍵程式碼

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"myTableCell";
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // 重點:不可省略 nil 判斷,否則搜尋時會因找不到對應 identifier 的 cell 而報錯
    if (cell == nil) {
        // 搜尋結果採用簡單的 cell style,而非自訂表視圖 cell 的 style
        cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                    reuseIdentifier:CellIdentifier];
        NSUInteger row = [indexPath row];
        NSDictionary *rowDict = [dataArr objectAtIndex:row];
        cell.textLabel.text = [rowDict objectForKey:@"itemName"];
        NSString *imagePath = [rowDict objectForKey:@"itemImagePath"];
        cell.imageView.image = [UIImage imageNamed:imagePath];
    }

    NSUInteger row = [indexPath row];
    NSDictionary *rowDict = [dataArr objectAtIndex:row];
    cell.label.text = [rowDict objectForKey:@"itemName"];
    NSString *imagePath = [rowDict objectForKey:@"itemImagePath"];
    cell.image.image = [UIImage imageNamed:imagePath];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

實作上的兩個提醒

  • 搜尋模式與一般模式的資料來源通常是兩個陣列(例如 dataArr 與 searchResultArr),記得依 tableView 是哪一個來決定要讀哪份資料,否則會出現 index 越界。
  • 上表同時設了 textLabel/imageView(系統屬性)與 label/image(自訂子視圖),實作時建議只用其中一套,避免視覺重疊。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved