Search code examples
iosswiftxcodeuibuttonibaction

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.


Solution

  • 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