首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UISearchController 更新自定義 UITableViewCell 內容不生效的解決方案

     編輯:程式設計綜合問答

問題現象

使用 UISearchController 進行搜尋篩選時,更新自定義 Cell 的 titleLabel 文字,日誌顯示賦值成功,但介面仍顯示舊數值。代碼片段顯示直接操作 Cell 的子視圖屬性。

根本原因

Cell 重用機制導致直接操作子視圖失效。 UITableView 透過 dequeueReusableCellWithIdentifier: 重用 Cell。若在配置 Cell 時(cellForRowAtIndexPath:)僅對子視圖賦值,而未在 Cell 子類中重寫 prepareForReuse 或 setNeedsLayout,重用時舊狀態殘留,且自動佈約可能覆蓋手動設置的屬性。

正確做法:封裝配置邏輯到 Cell 子類

1. 創建自定義 Cell 子類

@interface CustomCell : UITableViewCell
@property (nonatomic, strong) IBOutlet UILabel *titleLabel;
// 其他子視圖...
- (void)configureWithTitle:(NSString *)title;
@end

@implementation CustomCell
- (void)configureWithTitle:(NSString *)title {
    self.titleLabel.text = title;
    // 設置其他子視圖...
    [self setNeedsLayout]; // 觸發佈局更新
}

- (void)prepareForReuse {
    [super prepareForReuse];
    self.titleLabel.text = nil; // 重置狀態
}
@end

2. 在 cellForRowAtIndexPath 中調用配置方法

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" forIndexPath:indexPath];
    NSString *title = ...; // 根據搜尋結果獲取數據
    [cell configureWithTitle:title];
    return cell;
}

3. 確保註冊 Cell 類或 Storyboard/XIB 關聯正確

[tableView registerClass:[CustomCell class] forCellReuseIdentifier:@"CustomCell"]; // 代碼註冊
// 或 Storyboard 中設置 Custom Class 為 CustomCell,Identifier 為 "CustomCell"

為什麼之前的寫法失效?

  • 直接在控制器中 cell.titleLabel.text = ... 破壞了封裝,Cell 內部無法感知變化觸發佈局。
  • 重用 Cell 時,titleLabel 可能仍指向舊實例或被自動佈局約束覆蓋。
  • 未實現 prepareForReuse 導致舊數據殘留。

圖片參考

Cell 代碼截圖1

Cell 代碼截圖2

最佳實踐總結

  1. 數據配置邏輯內聚到 Cell 子類,暴露 configureWith... 方法。
  2. 重寫 prepareForReuse 重置所有動態屬性。
  3. 使用 Auto Layout 而非手動 frame,並在配置後調用 setNeedsLayout / layoutIfNeeded。
  4. 搜尋結果更新後調用 [tableView reloadData],而非嘗試單獨刷新可見 Cell。

結語

遵循「Cell 自己管理自己的視圖狀態」原則,即可解決 UISearchController 等篩選場景下自定義 Cell 顯示異常的問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved