same button perform multiple functions using selectors and update button text in iOS objective C
How do you make the same button perform more than 1 functi开发者_如何转开发on depending on certain conditions and accordingly change the text on the button? How do you do this using selectors?
I assume you want to change what method gets called by the state of the button or some other control...
-(IBAction)buttonClicked:(id)sender {
if ( someState ) {
[someObject doSomething];
}
else if (someOtherState) {
[someObject doSomethingElse];
}
}
just call different methods from a central selector. If you're changing the text on your button to signify what it's going to do, you could select the method to use based on the button's text value.
You can add as many actions for a button for a given event as you want.
Call addTarget:action:forControlEvents:
for each selector that is to be run for the event.
UIButton *aButton = [[UIButton alloc] initWithFrame:CGRectZero];
[aButton addTarget:self action:@selector(firstMethod) forControlEvents:UIControlEventTouchUpInside];
[aButton addTarget:self action:@selector(secondMethod) forControlEvents:UIControlEventTouchUpInside];
You can get the title by the button's currentTitle property. See: https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIButton_Class/UIButton/UIButton.html
A cleaner way to code, IMHO, would be to have a variable that tells you whether or not you are in PLAYING mode - use that, then your code will not break if you decide to change the button texts. In fact you would not want to have to look for different text values if you localize for different languages.
Then you can change your variable AND your button label whenever you go from play to pause, etc.
精彩评论