I have a UIButton
that should have 2 statuses - "Play" and "Pause"; i.e. - at the first time the user sees it it says "Play" and then whenever the user clicks it it should switch between "Play" and "Pause".
I managed to create the controller itself - the content is played and paused properly - but I cannot seem to change the UIButton Text Label text.
I use:
myButton.titleLabel.text = @"Play";
myButton.titleLabel.text = @"Pause";
It's not working. The text is not changing. I also tried [myButton.titleLabel setText:@"Pause"] and it's not working as well.
How can I set it?
It should be:
[myButton setTitle:@"Play" forState:UIControlStateNormal];
You need to pass the state
as well. You can check other state
's here.
You can then do something like this:
[myButton setTitle:@"Play" forState:UIControlStateNormal];
[myButton setTitle:@"Stop" forState:UIControlStateSelected];
SWIFT 4
myButton.setTitle("Pause", for: .normal)
I found this to be somewhat out of date since attributed strings were added. Apparently titles of buttons assigned in a storyboard are attributed strings. Attributed titles take precedence over NSString titles, so if you want to use a simple string as a title you have to remove the attributed title first. I did as below, though there may be a better way. You could, of course, make your new title also an attributed string.
[myButton setAttributedTitle: nil forState: 0xffff];
[myButton setTitle: @"Play" forState: UIControlStateNormal];
And if you want to load it on page load, and support localized language:
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if (self.flagToChangeLabel){
NSString* newBtnTitle = NSLocalizedString(@"LOCALIZED_KEY", nil);
[self.laterButton setTitle:newBtnTitle forState:UIControlStateNormal];
[self.laterButton setTitle:newBtnTitle forState:UIControlStateSelected];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With