将目标添加到UITableViewCell

时间:2020-01-28 14:29:41

标签: ios swift uitableview uibutton

我的UIButton中有CustomTableViewCell,并且我也叫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时出现“点击动画”,但是什么也没有发生。.

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

2 个答案:

答案 0 :(得分:1)

声明按钮时,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
}()

答案 1 :(得分:0)

创建按钮出口名称cellbuttonName或将其写在tableview中的任何其他代码代表cellForRowAtIndexPath

[self.cellbuttonName addTarget:self操作:@selector(updateDate :) forControlEvents:UIControlEventTouchUpInside];