質問

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.

役に立ちましたか?

解決

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

他のヒント

In addition to the tag property, or just in case you are already using the tag for some other purpose that would mean duplicate tag values for one or more different buttons, you can always set up an IBOutlet ivar to each button you needed to check, and then in the IBAction, do something like this:

- (IBAction)buttonReceived:(UIButton *)sender
{ 
    if (sender == myButtonA) {
       // processing for button A
    }
    else if (sender == myButtonB) {
       // processing for button B
    }
}

It is a bit more work, but it can come in handy at times.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top