Best method to determine the sender of an event

Gianni Costanzi picture Gianni Costanzi · Oct 15, 2011 · Viewed 6.9k times · Source

I have a simple question about event handling in iOS applications... suppose you have an app with some buttons that react to the TouchUpInside event calling the same action, what is the best way within the action method to understand what is the button that triggered the event? I know that it can be easily done using the title of the button, but I think it is not the best way if you have a localized app in which button text may change (unless it is possible to reverse the localization of the title, i.e. retrieve the original string from a localized string)... is there a good practice about this topic? Should I use some other property of buttons to distinguish among different buttons?

Thank you in advance for any help.

Answer

Eric picture Eric · Oct 15, 2011

There is something called a "Tag" that you can set for UIButtons, or anything that can respond to an event for that matter. If you are using Interface Builder, click the attributes inspector for the item and select a value for the tag (integer). In your code do something like this...

...

- (IBAction)buttonReceived:(id)sender
{ 
    if ([sender tag] == 1) {
       //Do something
    }
    else if ([sender tag] == 2) {
       //Do something else
    }
}