Reece Kenney Reece Kenney - 1 month ago 12
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

CellForRowAt
method:

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:

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. Why would this be happening? The function is expecting a parameter so the
:
is needed.

Answer

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

Try this instead:

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