How to Change textLabel property in UIButton programmatically in iOS?

Ohad Regev picture Ohad Regev · Jun 21, 2012 · Viewed 44.3k times · Source

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?

Answer

Rui Peres picture Rui Peres · Jun 21, 2012

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