7

我有一个这样的 UIButton 数组:

@property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *btn_Impact_Collection;

我有这个功能:

- (IBAction)impactAction:(id)sender;

在 XIB 文件中,我有九个按钮,每个按钮都通过引用插座集合连接到 btn_Impact_Collection 数组。此外,每个按钮的 Touch_inside 属性都连接到函数 ImpactAction。

现在,当单击按钮时,会调用 ImpactAction 函数,但是在此函数中,我怎么知道按下了哪个按钮?

提前感谢您的回答!

4

4 回答 4

16

将 sender 转换为 UIButton 类,这将为您提供单击按钮的实例。我没有 Xcode,但类似:

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

    // Then you can reference the title or a tag of the clicked button to do some further conditional logic if you want.
    if([btn.currentTitle isEqualToString:@"title of button"])
    {
        // do something.
    }
    else if(etc...)
}
于 2011-07-22T14:26:53.530 回答
13

在界面生成器(1-9)中为每个按钮设置标签,然后说

if ([sender tag] == 1) {
//First button was pressed, react.
}
else if ([sender tag] == 2) {
//Second button was pressed, react.
}
// Etc...
else {
//Last button was pressed, react.
}

其他所有的都一样,或者你可以把它放在一个开关里。

于 2011-07-22T14:28:03.373 回答
3

您可以:

- (void)buttonPressed:(id)sender
{
    for( UIButton *button in self.buttonCollection )
    {
        if( sender == button )
        {
            // sender is your button (eg. you can access its tag)
        }
    }
}
于 2013-03-12T13:21:14.753 回答
0

另一种选择.. 投射 sender 以检查它是否是 UIButton,然后切换 sender.tag:

if ([sender isMemberOfClass:[UIButton class]]) {
        switch ([sender tag]) {
            case 0:
                //do stuff for button with tag 0
                break;

            case 1:
                //do stuff for button with tag 1
                break;

            case 2:
                ....
                break;

            default:
                break;
        }
    }
于 2014-12-10T17:53:55.757 回答