Changing UIButton text

Julian Coltea picture Julian Coltea · Jul 10, 2012 · Viewed 94.2k times · Source

So I'm trying to update the text on a UIButton when I click it. I'm using the following line to change the text:

calibrationButton.titleLabel.text = @"Calibration";

I have verified that the text is changing, but when I run the app and I click on the button, it changes to "Calibration" for a split second and then goes right back to its default value. Any ideas why this might be happening? Is there some sort of refresh function I need to be calling?

Answer

Jesse Gumpo picture Jesse Gumpo · Jul 10, 2012

When laying out its subviews, a UIButton will set its titleLabel's text value using its own title values, so that you can set up to four different strings for the four states (normal, highlighted, selected, disabled).

Because of this feature, setting the titleLabel's text directly won't persist, and will be reset by the button when it lays out its subviews.

This is what you have to do to change the title text for a button's state.

[calibrationButton setTitle:@"Calibration" forState:UIControlStateNormal];