关于addTarget在UITableViewCell中的按钮

问题描述:

我不明白为什么我的UIButton中的addTarget不适用于特定情况。关于addTarget在UITableViewCell中的按钮

所以,有时我编程方式创建一个按钮,像一个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上测试它,它工作得很好。

谢谢!

+0

你的代码应该可以正常工作,并且不需要显式设置'isUserInteractionEnabled = true'。我从来没有尝试过让选择器不知道在哪里寻找方法。但是,就我所知,它会隐式地在'self'上调用函数。因此,请尝试使用该类的名称来限定选择器。例如'#selector(MyCustomTableViewCell.printMessage)'。 – Jonathan

+0

此外,这可能是不正确的,但我想我已经读过,你不应该在一个块中使用自己,因为它会被捕获。有人可能需要纠正我,如果我对此不正确。 – Jonathan

+0

嗨乔纳森。感谢您的留言。我试图做到这一点,但没有成功。这似乎不知道'self'不是'addTarget'在这种情况下所期待的,试图找出它:( – guarinex

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