Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Change textLabel property in UIButton programmatically in iOS?

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?

like image 447
Ohad Regev Avatar asked Jun 21 '12 09:06

Ohad Regev


4 Answers

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];
like image 167
Rui Peres Avatar answered Nov 07 '22 21:11

Rui Peres


SWIFT 4

myButton.setTitle("Pause", for: .normal)
like image 27
Wissa Avatar answered Nov 07 '22 19:11

Wissa


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];
like image 2
LostInTheTrees Avatar answered Nov 07 '22 19:11

LostInTheTrees


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];
    }
}
like image 1
Aviram Netanel Avatar answered Nov 07 '22 21:11

Aviram Netanel