Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define which button pressed if they both have same IBAction?

I have two UIButtons (I create them using IB), which connected to File's owner with the same IBAction, how can i define which of them are pressed?

like image 973
Tunyk Pavel Avatar asked Apr 04 '11 17:04

Tunyk Pavel


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 swift?

@IBAction is similar to @IBOutlet , but goes the other way: @IBOutlet is a way of connecting code to storyboard layouts, and @IBAction is a way of making storyboard layouts trigger code. This method takes one parameter, called sender . It's of type UIButton because we know that's what will be calling the method.

How do I select multiple buttons in Swift?

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.


2 Answers

Your action can be implemented like this:

- (IBAction) buttonTapped: (id) sender
// you can also replace id with UIButton*

Then inside this method you can check by -isEqual: method

- (IBAction) buttonTapped: (id) sender
{
   if ([sender isEqual:referenceToOneOfYourButtons]) {
   // do something
   }
   else if ([sender isEqual:referenceToTheOtherButton]) {
   ...
   }
}

Alternatively you can set up different values to tag property of buttons and then:

- (IBAction) buttonTapped: (UIButton*) sender
{
   const int firstButtonTag = 101;
   const int otherButtonTag = 102;

   if (sender.tag == firstButtonTag) {
   ...
   }
   else if (sender.tag == otherButtonTag) {
   ...
   }
}

You need to set up this tag either in your .xib or in code.

like image 67
Bartosz Ciechanowski Avatar answered Oct 04 '22 15:10

Bartosz Ciechanowski


Something along these lines... assuming button1 and button2 are in your header file.

- (IBAction)buttonPressed:(UIButton *)button {
        if (button == button1) {
        } else if (button == button2) {
        }
}

Or set the tag in Interface Builder and check for the tag.

- (IBAction)buttonPressed:(UIButton *)button {
            if (button.tag == 1) {
            } else if (button.tag == 2) {
            }
    }

Tags AREN'T zero-based. Use 1 or greater.

like image 44
Hobbes the Tige Avatar answered Oct 04 '22 16:10

Hobbes the Tige