我有两个 UIButtons(我使用 IB 创建它们),它们使用相同的 IBAction 连接到 File 的所有者,我如何定义它们中的哪一个被按下?
问问题
15505 次
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 或代码中设置此标记。
于 2011-04-04T18:01:21.067 回答
6
这些方面的东西......假设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 或更大。
于 2011-04-04T18:01:58.863 回答
0
将您的操作声明为
- (IBAction)someAction:(id)sender;
当控件发送 someAction 消息时,它将自己作为 sender 参数发送。
例如
- (IBAction)someAction:(id)sender {
NSLog(@"sender: %@", sender);
}
现在您知道是哪个控件发送了消息。
于 2011-04-04T18:01:26.760 回答
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;
}
于 2013-04-15T16:22:16.517 回答