Reece Kenney Reece Kenney - 1 year ago 97
iOS Question

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. This time however it is neither of those things.

I am creating a button in my TableView Cell by using this code in the


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

and I have declared the
method like so:

func showPeople(sender: UIButton) {

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() {

and change the selector to
it works fine which I guess means there is an issue with the way I'm passing the parameter. Why would this be happening? The function is expecting a parameter so the
is needed.

Answer Source

Looks like you're missing sender part in your selector.

Try this instead:

button.addTarget(self, action: #selector(ViewController.showPeople(sender:)), for: .touchUpInside)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download