Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing UIButton text

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?

like image 408
Julian Coltea Avatar asked Jul 10 '12 15:07

Julian Coltea


People also ask

How do I add text to UIButton?

Programmatically. To make a multi-line text in UIButton, you insert a new line character ( \n ) wherever you want in button title and set lineBreakMode to byWordWrapping . You can adjust text alignment with . textAlignment .

How do I change the text of a button in Swift?

You can omit UIControlState part and just write like button. setTitle("my text here", forState: . Normal) .


2 Answers

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]; 
like image 156
Jesse Gumpo Avatar answered Oct 15 '22 07:10

Jesse Gumpo


To set button text use the following method:

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

See UIButton class reference for more details... http://developer.apple.com/library/ios/#documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html

Or in Swift 3:

calibrationButton.setTitle("Calibration", for: .normal) 
like image 33
Ashley Mills Avatar answered Oct 15 '22 06:10

Ashley Mills