Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS: one IBAction for multiple buttons

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?

like image 685
cyclingIsBetter Avatar asked May 02 '11 14:05

cyclingIsBetter


People also ask

How do I use one IBAction for multiple buttons in Swift?

To connect the action to multiple buttons: in Interface Builder, right-click ViewController in the view hierarchy, then left-click to drag the action connection to each button.

What is IBAction in iOS?

IBAction and IBOutlets are used to hook up your interface made in Interface Builder with your controller. If you wouldn't use Interface Builder and build your interface completely in code, you could make a program without using them.

How do I link a button to another page in Xcode?

If you want to do this, right click drag (or control drag) from the button to the new view controller. This should make a grey line going from the first controller to the second one. You can then click on the little circle in the middle of the segue in interface builder to give it a name and specify the type.


2 Answers

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.)

like image 57
John Parker Avatar answered Oct 05 '22 19:10

John Parker


-(IBAction)myButtonAction:(id)sender {     if ([sender tag] == 0) {         // do something here     }     if ([sender tag] == 1) {         // Do something here     }     }  // in Other words  -(IBAction)myButtonAction:(id)sender {         switch ([sender tag]) {         case 0:             // Do something here             break;         case 1:            // Do something here              break;        default:            NSLog(@"Default Message here");             break; } 
like image 36
BigAppleBump Avatar answered Oct 05 '22 20:10

BigAppleBump