How to use a single IBAction for multiple buttons in iOS

Paul Franco
3 min readAug 13, 2020

iOS makes it very easy to connect multiple buttons to a single IBAction. I am going to assume that you already know how to create and IBAction for a specific button and that you just want to figure out how to connect other buttons that IBAction you have already connected in order to avoid having to create additional IBActions for each button.

In order to demonstrate this I created a simple application that has five different buttons and a label. The idea is that when you click on a button it changes the text on the label.

First you want to select the button on the Storyboard, you then press the Ctrl Key and while you are pressing down on the key you then click on the button and drag from the Storyboard onto the IBAction block in the ViewController. The IBAction block of code will appear highlighted and once you let go on the Ctrl button and the button on the mouse the connection will be created by Xcode.

To verify that Xcode made the connection between the buttons and the IBAction you can click on the ViewController button on top of the Storyboard and a modal will appear showing the different connections between the UI Elements in the storyboard and its ViewController.

ViewController and Storyboard connections

By now you might be thinking “Ok, the buttons are connected to the IBAction but how does the IBAction know which button was pressed?” Well UIButtons have many different properties we can use and one of them is the Tag property. You can assign a different number to each button giving it a distinct tag which can then be used in the IBAction in order to identify each button.

UIButton Tag Property

In our project, after assigning different numbers in the Tag property each one of the buttons we can now use those tags to identify which button was pressed and what code block should be executed.

I hope this article was useful and of some value to you. Happy coding.

--

--