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

11

我有两个UIButton(通过IB创建),它们都使用相同的IBAction连接到File's owner,如何确定哪一个被按下了?

4个回答

26

你可以像这样实现你的操作:

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

然后在这个方法内部,您可以使用-isEqual:方法进行检查。

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

或者,您可以设置不同的值来标记按钮属性,然后:

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

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

你需要在.xib文件或代码中设置此标签。


6

假设button1和button2在您的头文件中,大致如下...

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

或者在界面生成器中设置标签,并检查该标签。

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

标签不是从零开始的。请使用1或更大的数字。


0

将您的操作声明为

- (IBAction)someAction:(id)sender;

当一个控件发送someAction消息时,它会将自身作为sender参数一同发送。
例如:
- (IBAction)someAction:(id)sender {
    NSLog(@"sender: %@", sender);
}

现在你知道哪个控件发送了消息。


0
-(IBAction)myButtonAction:(id)sender {
    if ([sender tag] == 0) {
        // do something here
    }
    if ([sender tag] == 1) {
        // Do some think here
   }

}

// 换句话说

-(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;

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接