简体   繁体   English

传递参数时无法识别的选择器 - TableView 单元格中的 UIButton | 迅捷iOS

[英]Unrecognized Selector when Passing Parameter - UIButton in TableView Cell | Swift iOS

I've had this issue before but it usually due to not having a button hooked up in Storyboard or not passing a parameter when the function is expecting one, like most of the existing questions on here seem to suggest.我以前遇到过这个问题,但它通常是由于没有在 Storyboard 中连接按钮或在函数需要一个参数时没有传递参数,就像这里的大多数现有问题似乎暗示的那样。 This time however it is neither of those things.然而,这一次不是这些。

I am creating a button in my TableView Cell by using this code in the CellForRowAt method:我通过在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)

and I have declared the showPeople method like so:我已经像这样声明了showPeople方法:

func showPeople(sender: UIButton) {
    print("pressed")
}

When the button is pressed the program crashed with the following message:当按下按钮时,程序崩溃并显示以下消息:

showPeople: unrecognized selector sent to instance

But when I declare the method like so (remove the parameter):但是当我像这样声明方法时(删除参数):

func showPeople() {
    print("pressed")
}

and change the selector to Selector(("showPeople")) it works fine which I guess means there is an issue with the way I'm passing the parameter.并将选择Selector(("showPeople"))更改为Selector(("showPeople"))它工作正常,我猜这意味着我传递参数的方式存在问题。 Why would this be happening?为什么会发生这种情况? The function is expecting a parameter so the : is needed.因此,该函数需要一个参数:需要。

Looks like you're missing sender part in your selector.看起来您在选择器中缺少sender部分。

Try this instead:试试这个:

button.addTarget(self, action: #selector(ViewController.showPeople(sender:)), for: .touchUpInside)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM