Fabian Vergara
Fabian Vergara

Reputation: 43

Add same IBAction to multiple buttons. Latest Xcode, swift 3, iOS 10

Before I used to think this was really trivial... but now I can't seem to do it. I used to create multiple buttons, change their respective tags, then create one IBAction and it'd be called for all my buttons!

However, this was a while ago. Now I am trying to do the same and it doesn't seem to work. No matter what I do, my IBAction seems linked only to one button and it doesn't get triggered by any other.

I tried :

@IBAction func myAction(sender: UIButton) { }
@IBAction func myAction(_ sender: UIButton) { }
@IBAction func myAction(_ sender: Any) { }

And none of those works. Is this a bug? Is there a new way to do this? Am I forced to create individual actions for every button, despite the functionality of each being really familiar?

I googled and I can't just seem to make this work lol maybe there's something im missing now.

Upvotes: 0

Views: 1757

Answers (2)

Akila Upendra
Akila Upendra

Reputation: 27

Change @IBAction func myAction(_ sender: Any) { } to

@IBAction func myAction(_ sender: AnyObject) { }

So you can link any button to one single IBAction method.

(control + drag your buttons to "myAction" method's body in Assistant Editor)

Upvotes: 0

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

This is a bug in Xcode. Hope apple gets its bugs fixed soon.

The default signature of the IBAction when you drag from button looks something like

@IBAction func meHere(_ sender: Any) {
    //something here
 }

Now if you add another button and try to set the same IBAction to the button it wont allow (Only apple knows why though)

Solution :

Change method signature to

@IBAction func meHere(_ sender: UIButton) {
}

Change Any to Specific UIComponent. Now control drag from your IBAction to your new button everything will be fine :)

enter image description here As you can see both me and you button are hooked to same IBAction :)

enter image description here Happy coding

Upvotes: 1

Related Questions