在自訂的表視圖上加入搜尋欄,是常見需求。本文記錄實作時踩到的一個關鍵細節:搜尋結果與一般列表共用同一個 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(自訂子視圖),實作時建議只用其中一套,避免視覺重疊。