Detect which button is pressed with an UIButton Array

时光怂恿深爱的人放手 提交于 2019-11-30 04:04:25

Cast sender to UIButton class, and that will give you the instance of the clicked button. I don't have Xcode with me but something like:

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...)
}

Set tags for each button in interface builder (1-9), then say

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.
}

And the same for all the others, or you could put it in a switch.

Rather than do a string check on the title (which is slow and can be tedious) you can:

- (void)buttonPressed:(id)sender
{
    for( UIButton *button in self.buttonCollection )
    {
        if( sender == button )
        {
            // sender is your button (eg. you can access its tag)
        }
    }
}

Another option.. Cast sender to check if it's a UIButton, then switch 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;
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!