我以前遇到过这个问题,但通常是因为没有在 Storyboard 中连接按钮,或者在函数需要一个参数时没有传递参数,就像这里的大多数现有问题似乎暗示的那样。然而这一次它不是那些东西。
我在 CellForRowAt
方法中使用以下代码在我的 TableView Cell 中创建一个按钮:
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"))
它工作正常,我猜这意味着我传递参数的方式存在问题。为什么会这样?该函数需要一个参数,因此需要 :
。
最佳答案
看起来您的选择器中缺少 sender
部分。
试试这个:
button.addTarget(self, action: #selector(ViewController.showPeople(sender:)), for: .touchUpInside)
关于ios - 传递参数时无法识别的选择器 - TableView 单元格中的 UIButton | swift iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39980736/