Detect which button is pressed with an UIButton Array

benza picture benza · Jul 22, 2011 · Viewed 17.3k times · Source

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!

Answer

mservidio picture mservidio · Jul 22, 2011

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