Ohad Regev
Ohad Regev

Reputation: 5711

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?

Upvotes: 32

Views: 47594

Answers (4)

Rui Peres
Rui Peres

Reputation: 25917

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];

Upvotes: 70

Wissa
Wissa

Reputation: 1592

SWIFT 4

myButton.setTitle("Pause", for: .normal)

Upvotes: 9

LostInTheTrees
LostInTheTrees

Reputation: 1145

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];

Upvotes: 2

Aviram Netanel
Aviram Netanel

Reputation: 13625

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

Upvotes: 1

Related Questions