[英]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.