如何确定从三个按钮中按下了哪个按钮

时间:2013-10-09 20:19:12

标签: ios ios6 uibutton uistoryboardsegue

我有三个按钮,他们都做同样的事情执行一个segue。所有都链接到同一个连接。

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

我需要做的是确定prepareForSegue方法中按下的按钮。如何判断按下三个按钮中的哪一个。

不查看按钮上的措辞/文字,因为这会改变本地化。

4 个答案:

答案 0 :(得分:8)

你可以使用Tag Value来设置Taped Button,假设你有例如树按钮: -

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

然后设置按钮标签,如: -

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

并为每个Button设置相同IBAction并: -

[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]; 
      }

}

有关信息

如果您在id中使用IBAction,那么您将获得以下按钮对象: -

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

答案 1 :(得分:0)

将按钮的标记存储在实例变量中,并在调用prepareForSegue时查看该变量

答案 2 :(得分:0)

您可以转发发送到sender的{​​{1}}参数,因为这是按下的按钮。也就是说,如果你这样做:

difficultyButtonPressed:

发送到- (IBAction)difficultyButtonPressed:(id)sender { // Any difficulty selected [self performSegueWithIdentifier:@"mainGameTurnGuess" sender:sender]; } 的{​​{1}}参数将是按下的按钮。

答案 3 :(得分:0)

您还可以使用Restoration Id按钮。在prepareForSegue中,您可以执行以下操作:

UIButton *btnSender;
if ([sender isMemberOfClass:[UIButton class]])
{
    btnSender = (UIButton *)sender;
}

// Then you can reference the Restoration Id or a tag of the clicked button to do further conditional logic if you want.
if([btnSender.restorationIdentifier isEqualToString:@"myBtn1"])
{
   //do something
}

我引用苹果文档:

  

由于segues可以从多个源触发,因此您可以使用segue和sender参数中的信息来消除应用中不同逻辑路径之间的歧义。例如,如果segue源自表视图,则sender参数将标识用户点击的表视图单元格。您可以使用该信息在目标视图控制器上设置数据