Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - set UIButton title regardless of state

Is there a way in Swift to change a UIButton's title/label for all states? I am setting the title of the UIButton to something, but when it is unhighlighted the label changes to what it was previously.

Thanks

like image 229
Arthur Avatar asked Mar 11 '16 06:03

Arthur


2 Answers

There isn't a method to set the title for all states at once, however if you never set the title for states other than the normal state, the unset states will default to the normal title.

From the docs

If a title is not specified for a state, the default behavior is to use the title associated with the UIControlStateNormal state. If the value for UIControlStateNormal is not set, then the property defaults to a system value.

So just call

button.setTitle("Button text", for:.normal)

Without setting the title for other states. If you need to set different titles for the other states, you'll need to set them back every time you change the button's title.

like image 97
Josh Heald Avatar answered Oct 04 '22 09:10

Josh Heald


setTitle now takes an OptionSet - so you need to pass in an empty set.

Syntax is now:

button.setTitle("Button Text", for: [])
like image 21
David Crow Avatar answered Oct 04 '22 09:10

David Crow