【问题标题】:Add target to UIButton inside UITableViewCell将目标添加到 UITableViewCell 内的 UIButton
【发布时间】:2020-05-13 23:58:24
【问题描述】:

我的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 时出现“点击动画”但没有任何反应..

有人知道为什么会发生这种情况以及我该如何适应吗?

【问题讨论】:

    标签: ios swift uitableview uibutton


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多