如何定义哪个button被按下,如果他们都有相同的IBAction?

我有两个UIButtons(我创build它们使用IB),它连接到文件的所有者与相同的IBAction,我怎样才能定义他们被按下?

你的行为可以像这样实现:

- (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]) { ... } } 

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

 - (IBAction) buttonTapped: (UIButton*) sender { const int firstButtonTag = 101; const int otherButtonTag = 102; if (sender.tag == firstButtonTag) { ... } else if (sender.tag == otherButtonTag) { ... } } 

您需要在.xib或代码中设置此标记。

沿着这些线的东西…假设button1和button2在你的头文件。

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

或者在Interface Builder中设置标签并检查标签。

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

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

宣布你的行动为

 - (IBAction)someAction:(id)sender; 

当一个控件发送someAction消息时,它将作为sender参数发送。

例如

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

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

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

}