Tunyk Pavel
Tunyk Pavel

Reputation: 2493

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?

Upvotes: 11

Views: 15556

Answers (4)

BigAppleBump
BigAppleBump

Reputation: 1096

-(IBAction)myButtonAction:(id)sender {

    if ([sender tag] == 0) {
        // do something here
    }
    if ([sender tag] == 1) {
        // Do some think here
   }

}

// in Other words

-(IBAction)myButtonAction:(id)sender {

     NSLog(@"Button Tag is : %i",[sender tag]);

    switch ([sender tag]) {
    case 0:
        // Do some think here
        break;
    case 1:
       // Do some think here
         break;
   default:
       NSLog(@"Default Message here");
        break;

}

Upvotes: 0

Bartosz Ciechanowski
Bartosz Ciechanowski

Reputation: 10333

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.

Upvotes: 26

Hobbes the Tige
Hobbes the Tige

Reputation: 3821

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.

Upvotes: 6

Terry Wilcox
Terry Wilcox

Reputation: 9040

Declare your action as

- (IBAction)someAction:(id)sender;

When a control sends the someAction message, it will send itself along as the sender parameter.

e.g.

- (IBAction)someAction:(id)sender {
    NSLog(@"sender: %@", sender);
}

Now you know which control sent the message.

Upvotes: 0

Related Questions