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

iOS UITableViewCell 重用導致視圖重疊:正確的 cellForRowAtIndexPath 寫法

     編輯:程式設計綜合問答

問題現象

表格滾動時單元格內容重疊、重複。代碼中創建子視圖(UIImageView、UILabel、UIButton 等)並直接 addSubview: 到 cell.contentView,但缺少重用邏輯控制。

錯誤代碼片段

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:myIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:... reuseIdentifier:myIdentifier];
}
// 每次都無條件添加子視圖
[cell.contentView addSubview:backImage];
[cell.contentView addSubview:detailTextLabel];
// ...

根本原因

dequeueReusableCellWithIdentifier: 返回的復用 cell 已包含上次添加的子視圖。若不清理或判斷,每次調用都會疊加新視圖,導致重疊和內存洩漏。

正確寫法:僅在創建時添加子視圖

static NSString *myIdentifier = @"myIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:myIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myIdentifier];
    // 僅在 cell 初次創建時添加子視圖,並設置 tag 便於後續獲取
    UIImageView *backImage = [[UIImageView alloc] initWithFrame:...];
    backImage.tag = 100;
    [cell.contentView addSubview:backImage];
    // 其他子視圖同理設置 tag...
}

// 通過 tag 獲取子視圖並更新數據
UIImageView *backImage = (UIImageView *)[cell.contentView viewWithTag:100];
backImage.image = [UIImage imageNamed:@"shop-bg.png"];
// 更新 label、button 等...

現代最佳實踐:使用自定義 Cell 類

創建 CustomCell : UITableViewCell,在 initWithStyle:reuseIdentifier: 中佈局子視圖並暴露屬性(IBOutlet),cellForRowAtIndexPath 僅負責數據綁定,代碼更清晰、性能更好。

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