UITableView单元格内UIButton点击无响应,如何修复?
解决按钮点击无响应的问题
你需要调整以下几个地方来修复按钮点击无响应的问题:
1. 将按钮添加到Cell的contentView而非Cell本身
UITableViewCell的contentView是专门承载自定义子视图的容器,直接把按钮添加到Cell实例上,可能会被contentView遮挡,导致无法接收触摸事件。修改MyCustomCell的初始化代码:
class MyCustomCell: UITableViewCell { let button = UIButton() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) button.setTitle("Get to it", for: .normal) button.backgroundColor = .blue // 把按钮添加到contentView上,而不是cell本身 contentView.addSubview(button) button.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ button.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), button.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), button.widthAnchor.constraint(equalToConstant: 100), button.heightAnchor.constraint(equalToConstant: 40) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
2. 避免重复添加Target(优化)
每次Cell被复用时,你都在cellForRowAt里调用addTarget,会导致同一个按钮绑定多个相同的响应方法。建议在复用前先移除旧的Target,再添加新的:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 使用自定义标识符,避免和系统Cell混淆 let cell = tableView.dequeueReusableCell(withIdentifier: "MyCustomCell", for: indexPath) as! MyCustomCell if let model = viewsArray[indexPath.row] { cell.textLabel?.text = model.name cell.textLabel?.textColor = .systemPink // 先移除旧绑定,再添加新的Target cell.button.removeTarget(nil, action: nil, for: .allEvents) cell.button.addTarget(self, action: #selector(actbuttonFuncCall), for: .touchUpInside) } return cell }
3. 确保单元格注册的标识符匹配
检查viewDidLoad里的注册代码,确保标识符和cellForRowAt中使用的一致:
override func viewDidLoad() { super.viewDidLoad() tableView.register(MyCustomCell.self, forCellReuseIdentifier: "MyCustomCell") // 其他初始化代码... }
完成以上修改后,按钮的点击事件应该就能正常触发,控制台会打印"button clicked"。
内容的提问来源于stack exchange,提问作者willd
相关产品推荐
相关产品推荐

