Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect which button is pressed with an UIButton Array

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 connected 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!

like image 469
benza Avatar asked Jul 22 '11 14:07

benza


3 Answers

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...)
}
like image 187
mservidio Avatar answered Nov 07 '22 06:11

mservidio


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.

like image 40
Alex Coplan Avatar answered Nov 07 '22 05:11

Alex Coplan


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)
        }
    }
}
like image 26
cleverbit Avatar answered Nov 07 '22 05:11

cleverbit