How to use the same function with multiple buttons

Jay Wilson
2 min readMay 30, 2019

Some iOS apps require buttons to utilize the same function when tapped, think number buttons in a Calculator App. A number button on a calculator will perform the same action, store the number associated with it. Instead of declaring a function for each button, create one function that uses the button tag.

Find the GitHub repo here.

Create the project and the “UI”

Create a new iOS Single View App and give it a product name of “buttons to action”.

Add two buttons to Main.storyboard. You can add style to the buttons to make it easier to see. I'm going to add a background and make a bit larger.

Add a label to Main.storyboard.

Add a tag value to buttons

When utilizing the same function on both buttons, there needs to be a way to distinguish between the two buttons. A way to do this is to utilize Tag. This can be found in the inspector.

Set the button on the left to have a Tag of 0, and set the button on the right to have a Tag of 1.

Add the label…

--

--

Jay Wilson
Jay Wilson

Written by Jay Wilson

I like to solve problems using Swift, make YouTube videos, and take photos. I also really enjoy a good cup of coffee.