将目标添加到UITableViewCell中的UIButton



我的CustomTableViewCell里面有UIButton,我也打电话给addTarget

let eyeButton: UIButton = {
let v = UIButton()
v.addTarget(self, action: #selector(eyeButtonTapped), for: .touchUpInside)
v.setImage(UIImage(named: "eyeOpen"), for: .normal)
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()

但是,此函数未被调用(也在CustomTableViewCell中声明(:

@objc func eyeButtonTapped(){
print("Hi")
}

当我单击button时有一个"点击动画",但没有任何反应。

任何人都知道为什么会发生这种情况以及我如何适应它?

声明按钮时,此时self不存在。

在设置功能中添加目标,或将声明更改为lazy var

lazy var eyeButton: UIButton = {
let v = UIButton()
v.addTarget(self, action: #selector(eyeButtonTapped), for: .touchUpInside)
v.setImage(UIImage(named: "eyeOpen"), for: .normal)
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()

创建按钮 插座名称 cellbuttonName 或除在 tableviewdelegate cellForRowAtIndexPath 中编写该代码以外的任何其他代码

[self.cellbuttonName addTarget:self action:@selector(updateDate:( forControlEvents:UIControlEventTouchUpInside];

最新更新