【问题标题】:About addTarget for a button inside a UITableViewCell关于 UITableViewCell 内按钮的 addTarget
【发布时间】:2018-01-05 02:22:12
【问题描述】:

我无法理解为什么我的 UIButton 中的 addTarget 在特定情况下不起作用。

所以,有一个UITableViewCell,我在其中以编程方式创建了一个按钮,例如:

let myClickButton : UIButton = {
    let button = UIButton()
    button.setTitle("Hit Test", for: .normal)
    button.tintColor = UIColor.white
    button.addTarget(self, action: #selector(printMessage), for: .touchUpInside)
    button.isUserInteractionEnabled = true
    return button
}()

而且,我的UITableViewCell 类中还有一个按钮应该调用的函数:

func printMessage(){
    print("button was clicked")
}

但是,printMessage 函数从未被调用,并且控制台中没有错误。你能帮我理解这个案子有什么问题吗?这似乎是在UITableViewCell 中的问题,因为我肯定在常规viewController 上对其进行了测试,并且效果很好。

非常感谢!

【问题讨论】:

  • 您的代码应该可以正常工作并且无需显式设置isUserInteractionEnabled = true。我从来没有尝试在不让运行时知道在哪里寻找方法的情况下传递选择器。但是,据我所知,它将隐式调用self 上的函数。因此,请尝试使用类名来限定选择器。例如,#selector(MyCustomTableViewCell.printMessage).
  • 另外,这可能是不正确的,但我想我已经读过你不应该在块中使用 self ,因为它会被捕获。如果我对此不正确,可能需要有人纠正我。
  • 嗨乔纳森。谢谢你的留言。我试图这样做,但没有成功。在这种情况下,self 似乎不是addTarget 所期望的,试图弄清楚:(
  • Hmmm.... 根据按钮的关闭位置,我会在 UITableViewCell 被实例化后尝试设置目标。除此之外,如果没有看到更多代码,我不确定问题出在哪里。
  • 天哪!有效。我在awakeFromNib 方法上添加了目标。谢谢你,乔纳森!非常感谢!

标签: ios uitableview swift3 uibutton addtarget


【解决方案1】:

根据按钮的关闭位置,我会在 UITableViewCell 被实例化后尝试设置目标。除此之外,如果没有看到更多代码,我不确定问题出在哪里。

【讨论】:

    猜你喜欢
    • 2018-08-27
    • 1970-01-01
    • 2013-03-13
    • 2017-08-30
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    相关资源
    最近更新 更多