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?
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.
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.
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.
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.)
-(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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With