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

iOS UITableView Cell 內 Button 滾動亂跑:Cell 重用機制導致

     編輯:程式設計綜合問答

問題根因

在 cellForRowAtIndexPath 中直接 addSubview Button,且用 _isAddImageViewLoad 布林旗標控制只加一次。但 UITableView 會重用 Cell,滾動時舊 Cell 被重用,Button 仍留在 ContentView 上,導致位置錯位、重複疊加。

正確模式:自訂 Cell 類別 + 模型驅動

  1. 建立 CustomCell : UITableViewCell,在 initWithStyle:reuseIdentifier: 中一次性建立 Button、設定約束/Frame、加入 contentView。
  2. 提供 configure(with: Model) 方法,根據資料更新 Button 圖片、標題、隱顯狀態。
  3. cellForRowAtIndexPath 僅負責取得/建立 Cell 並呼叫 configure。

代碼範例

// CustomCell.h
@interface CustomCell : UITableViewCell
@property (nonatomic, strong) UIButton *actionButton;
- (void)configureWithTitle:(NSString *)title showButton:(BOOL)show;
@end

// CustomCell.m
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _actionButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_actionButton setImage:[UIImage imageNamed:@"AddImage"] forState:UIControlStateNormal];
        _actionButton.frame = CGRectMake(110, 10, 110, 110);
        [self.contentView addSubview:_actionButton];
    }
    return self;
}
- (void)configureWithTitle:(NSString *)title showButton:(BOOL)show {
    self.textLabel.text = title;
    self.actionButton.hidden = !show;
}

// ViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" forIndexPath:indexPath];
    BOOL showBtn = (indexPath.section == 0 && indexPath.row == 0);
    [cell configureWithTitle:itemTitle showButton:showBtn];
    return cell;
}

關鍵原則

  • Cell 內子 View 只在 init 建立一次,重用時自動保留。
  • 所有狀態(文字、圖片、隱顯)在 configure 中根據模型重設,不依賴旗標。
  • Button 觸控事件建議用 addTarget:action:forControlEvents: 指向 Controller 方法,並在 configure 中設定 tag = indexPath.row 以識別來源。

補充:iOS 13+ 建議改用 UICollectionView + Diffable Data Source

更現代、效能更好、避免手動索引管理錯誤。

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