1
我不明白爲什麼我的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
上測試它,它工作得很好。
謝謝!
你的代碼應該可以正常工作,並且不需要顯式設置'isUserInteractionEnabled = true'。我從來沒有嘗試過讓選擇器不知道在哪裏尋找方法。但是,就我所知,它會隱式地在'self'上調用函數。因此,請嘗試使用該類的名稱來限定選擇器。例如'#selector(MyCustomTableViewCell.printMessage)'。 – Jonathan
此外,這可能是不正確的,但我想我已經讀過,你不應該在一個塊中使用自己,因爲它會被捕獲。有人可能需要糾正我,如果我對此不正確。 – Jonathan
嗨喬納森。感謝您的留言。我試圖做到這一點,但沒有成功。這似乎不知道'self'不是'addTarget'在這種情況下所期待的,試圖找出它:( – guarinex