[英]Unrecognized Selector when Passing Parameter - UIButton in TableView Cell | Swift iOS
我以前遇到過這個問題,但它通常是由於沒有在 Storyboard 中連接按鈕或在函數需要一個參數時沒有傳遞參數,就像這里的大多數現有問題似乎暗示的那樣。 然而,這一次不是這些。
我通過在CellForRowAt
方法中使用此代碼在我的 TableView 單元格中創建一個按鈕:
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
button.addTarget(self, action: Selector(("showPeople:")), for: UIControlEvents.touchUpInside)
button.tag = indexPath.row
cell.addSubview(button)
我已經像這樣聲明了showPeople
方法:
func showPeople(sender: UIButton) {
print("pressed")
}
當按下按鈕時,程序崩潰並顯示以下消息:
showPeople: unrecognized selector sent to instance
但是當我像這樣聲明方法時(刪除參數):
func showPeople() {
print("pressed")
}
並將選擇Selector(("showPeople"))
更改為Selector(("showPeople"))
它工作正常,我猜這意味着我傳遞參數的方式存在問題。 為什么會發生這種情況? 因此,該函數需要一個參數:
需要。
看起來您在選擇器中缺少sender
部分。
試試這個:
button.addTarget(self, action: #selector(ViewController.showPeople(sender:)), for: .touchUpInside)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.