You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TableView单元格内按钮无响应问题排查求助

解决TableView单元格按钮点击无响应的问题

问题排查与修复步骤

1. 修复单元格类的语法错误

你的ReservationCell中setSelected方法存在语法错误(括号未闭合),这会导致单元格初始化异常,直接影响按钮交互逻辑:

// 错误代码
override func setSelected(_ selected: Bool, animated: Bool {
    super.setSelected(selected, animated: animated)
}

// 修复后
override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}

2. 移除重复的事件绑定,统一逻辑

你在两处给按钮绑定了点击事件,重复绑定会导致响应混乱,建议二选一处理:

方案一:保留ViewController中的事件处理

删除ReservationCell中空实现的@IBAction方法:

// 删除这段代码
@IBAction func btnCellTapped(_ sender: UIButton) {

}

同时修正ProfileViewController中addTarget的方法名空格问题:

// 原代码的空格会导致方法识别失败
cell.cancelReservation.addTarget(self, action: #selector(btnCellTapped(sender:)), for: .touchUpInside)

方案二:用单元格闭包回调解耦(推荐)

让单元格自己管理按钮点击,通过闭包把事件传递给ViewController:

class ReservationCell: UITableViewCell {
    // ... 原有IBOutlet
    
    // 定义回调闭包
    var onCancelTapped: (() -> Void)?
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
    
    @IBAction func btnCellTapped(_ sender: UIButton) {
        onCancelTapped?()
    }
}

然后在cellForRowAt中设置闭包:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: K.reusableCellReservations, for: indexPath) as! ReservationCell
    // ... 原有赋值代码
    
    // 设置点击回调
    cell.onCancelTapped = {
        print("pressed")
    }
    return cell
}

记得删掉cell.cancelReservation.addTarget(...)这段代码。

3. 检查视图交互属性

确认Storyboard/XIB中:

  • 按钮的User Interaction Enabled处于勾选状态
  • 按钮没有被其他视图完全遮挡
  • 单元格本身的User Interaction Enabled也为勾选状态

4. 检查TableView交互设置

确保TableView的User Interaction Enabled是开启状态,没有全局禁用交互。


内容的提问来源于stack exchange,提问作者Branislav Fekeč

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 02:35:25