IOS: one IBAction for multiple buttons

cyclingIsBetter picture cyclingIsBetter · May 2, 2011 · Viewed 61.8k times · Source

In my project I must control action of 40 buttons, but I don't want to create 40 IBAction, can I use only a IBAction, how?

Answer

John Parker picture John Parker · May 2, 2011

If you're using interface builder to create the buttons, simply point them at the same IBAction in the relevant class.

You can then differentiate between the buttons within the IBAction method either by reading the text from the button...

- (IBAction)buttonClicked:(id)sender {
    NSLog(@"Button pressed: %@", [sender currentTitle]);    
}

...or by setting the tag property in Xcode and reading it back via [sender tag]. (If you use this approach, start the tags at 1, as 0 is the default and hence of little use.)