开发者

Detect which button is pressed with an UIButton Array

开发者 https://www.devze.com 2023-03-22 19:10 出处:网络
I have an UIButton array like this: @property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *btn_Impact_Collection;

I have an UIButton array like this:

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

and I have this function:

- (IBAction)impactAction:(id)sender;

In the XIB file I have nine button, each button is connected to btn_Impact_Collection Array with the Referencing Outlet Collection. Moreover the Touch_inside property of each button is con开发者_JAVA技巧nected to the function ImpactAction.

Now, when a button is clicked the ImpactAction function is called, but inside this function, how can i know which button is pressed?

Thanks in advance for the answer!


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;
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消