表格滾動時單元格內容重疊、重複。代碼中創建子視圖(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 等...
創建 CustomCell : UITableViewCell,在 initWithStyle:reuseIdentifier: 中佈局子視圖並暴露屬性(IBOutlet),cellForRowAtIndexPath 僅負責數據綁定,代碼更清晰、性能更好。