Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 and unrecognized selector sent to instance error for button creation [duplicate]

After we start using Swift 3 we have been faced with this 'unrecognized selector sent to instance! error and could not find the solution at reasonable time. All the answers we have encountered for older version of Swift. This is the declaration of action we came up with

     testbutton.addTarget(self, action: Selector("testButtonAction:"), for: UIControlEvents.touchDown)

and this is the "corrected" version by Xcode but neither of them is working.

     testbutton.addTarget(self, action: Selector(("testButtonAction:")), for: UIControlEvents.touchDown)

This is the action function.

       func testButtonAction(sender: UIButton!) {

            print("Button tapped")

          }
like image 362
Hope Avatar asked Nov 29 '25 02:11

Hope


2 Answers

The correct syntax for Swift 3 is:

testbutton.addTarget(self, action: #selector(testButtonAction(sender:)), for: UIControlEvents.touchDown)

Any mistakes here will now be picked up at compile time rather than run time.

like image 177
Vince O'Sullivan Avatar answered Dec 02 '25 05:12

Vince O'Sullivan


It should be like this:

testButton.addTarget(self, action: #selector(YourViewController.testButtonAction(sender:)), for: UIControlEvents.touchDown)
like image 34
Dharmesh Kheni Avatar answered Dec 02 '25 05:12

Dharmesh Kheni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!