Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine which button was pressed out of three buttons

I have three buttons, they all do the same thing perform a segue. All linked to the same connection.

- (IBAction)difficultyButtonPressed:(id)sender {
    // Any difficulty selected
    [self performSegueWithIdentifier:@"mainGameTurnGuess" sender:self];
}

What I need to do is determine what button was pressed in the prepareForSegue method. How can I tell which out of the three buttons are pressed.

Without looking at the wording/text on the button as this would change for localisation.

like image 875
StuartM Avatar asked Feb 15 '23 01:02

StuartM


1 Answers

You can ditermine the Taped Button using Tag Value suppose you have tree Button for Example:-

@property (nonatomic, strong)  UIButton *btn1;
@property (nonatomic, strong) UIButton *btn2;
@property (nonatomic, strong) UIButton *btn3;

Then set Tag of Button like:-

btn1.tag=1;
btn2.tag=2;
btn3.tag=3;

and set Same IBAction for each Button and:-

[btn1 addTarget:self action:@selector(difficultyButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

[btn2 addTarget:self action:@selector(difficultyButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

[btn3 addTarget:self action:@selector(difficultyButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

- (IBAction)difficultyButtonPressed:(UIButton*)sender
{
 NSLog(@"Button tag is %d",sender.tag);

     // you can use if else condition using sender.tag  like

      if(sender.tag==1)//first button related identifire
      {
           [self performSegueWithIdentifier:@"mainGameTurnGuess_FirstButtonIdentirier" sender:sender]; 
      }
      else if(sender.tag==2)//second button related identifier
      {
            [self performSegueWithIdentifier:@"mainGameTurnGuess_secondButtonIdentirier" sender:sender]; 
      }
      else   //Third button related identifier
      {
            [self performSegueWithIdentifier:@"mainGameTurnGuess_ThirdButtonIdentirier" sender:sender]; 
      }

}

For Info

If you are using id in IBAction then you get the Button Object like:-

- (IBAction)difficultyButtonPressed:(id)sender {
    UIButton *button = (UIButton *)sender;
    NSLog(@"Button tag is %d",button.tag);
}
like image 83
Nitin Gohel Avatar answered Apr 09 '23 00:04

Nitin Gohel