Changing text of UIButton programmatically swift

rocket101 picture rocket101 · Oct 12, 2014 · Viewed 257.9k times · Source

Simple question here. I have a UIButton, currencySelector, and I want to programmatically change the text. Here's what I have:

currencySelector.text = "foobar"

Xcode gives me the error "Expected Declaration". What am I doing wrong, and how can I make the button's text change?

Answer

Gal Marom picture Gal Marom · Oct 12, 2014

In Swift 3, 4, 5:

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

Otherwise:

button.setTitle("Button Title", forState: UIControlState.Normal)

Also an @IBOutlet has to declared for the button.