31

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?

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
Ohad Regev
  • 5,641
  • 12
  • 60
  • 84

4 Answers4

69

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];
Rui Peres
  • 25,741
  • 9
  • 87
  • 137
9

SWIFT 4

myButton.setTitle("Pause", for: .normal)
Faysal Ahmed
  • 7,501
  • 5
  • 28
  • 50
Wissa
  • 1,444
  • 20
  • 24
2

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];
LostInTheTrees
  • 1,135
  • 9
  • 19
1

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];
    }
}
Aviram Netanel
  • 12,633
  • 9
  • 45
  • 69