简体   繁体   English

如果它们都具有相同的IBAction,如何定义按下哪个按钮?

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

我有两个UIButtons(我使用IB创建它们),它使用相同的IBAction连接到File的所有者,我如何定义哪些被按下?

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 然后在此方法中,您可以通过-isEqual:方法进行检查

- (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. 您需要在.xib或代码中设置此标记。

Something along these lines... assuming button1 and button2 are in your header file. 沿着这些方向的东西...假设button1和button2在你的头文件中。

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

Or set the tag in Interface Builder and check for the tag. 或者在Interface Builder中设置标签并检查标签。

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

Tags AREN'T zero-based. 标签不是从零开始的。 Use 1 or greater. 使用1或更大。

-(IBAction)myButtonAction:(id)sender { - (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 { - (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;

} }

Declare your action as 声明你的行动为

- (IBAction)someAction:(id)sender;

When a control sends the someAction message, it will send itself along as the sender parameter. 当控件发送someAction消息时,它将自己作为sender参数发送。

eg 例如

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

Now you know which control sent the message. 现在你知道哪个控件发送了消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM