ceismail
ceismail

Reputation: 31

Argument of '#selector' does not refer to an '@objc' method

I created UIButton name is plusButton and UILabel name is itemLabel programmatically and I added target for this button;

plusButton.addTarget(self, action: #selector(plusButtonClicked(itemLabel)), for: UIControlEvents.touchUpInside)

@objc func plusButtonClicked(_ sender : UILabel){
   //MY CODE
}

I'm getting "Argument of '#selector' does not refer to an '@objc' method, property, or initializer" error. When I remove the parameter in the function there's no any error. But, when it's a parameter in the function I'm getting error.

Upvotes: 1

Views: 10337

Answers (3)

raju kumar sharma
raju kumar sharma

Reputation: 41

You have used the wrong selector in your code. The selector should be written like #selector(plusButtonClicked(_ :) for your function.

Over all your code should be like this...

plusButton.addTarget(self, action: #selector(plusButtonClicked(_ :)), for:   UIControlEvents.touchUpInside)

@objc func plusButtonClicked(sender:Any) {
    let button = sender as? UIButton
    // you can do whatever want with button.
}

Upvotes: 3

matt
matt

Reputation: 536009

This is wrong:

@objc func plusButtonClicked(_ sender : UILabel)
                                        ^^^^^^^

You cannot send a label as parameter for a button tap. The parameter is the button and you cannot change that.

You cannot work around those rules by trying to change the argument in the selector. Selectors don’t have arguments.

You need some other way to work out which is the right label.

Upvotes: 1

Bhavin Kansagara
Bhavin Kansagara

Reputation: 2916

It should be like:

plusButton.addTarget(self, action: #selector(plusButtonClicked(_ :)), for: UIControlEvents.touchUpInside)

Update it.

Upvotes: 0

Related Questions