Simple question here. I have a UIButton, currencySelector, and I want to programmatically change the text. Here\'s what I have:
currencySelector.text = \"foo
//for normal state:
btnSecurite.setTitle("TextHear", for: .normal)
swift 4.2 and above
using button's IBOutlet
btnOutlet.setTitle("New Title", for: .normal)
using button's IBAction
@IBAction func btnAction(_ sender: UIButton) {
sender.setTitle("New Title", for: .normal)
}
Swift 3
When you make the @IBAction:
@IBAction func btnAction(_ sender: UIButton) {
sender.setTitle("string goes here", for: .normal)
}
This sets the sender as UIButton (instead of Any) so it targets the btnAction as a UIButton
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
.
Just a clarification for those new to Swift and iOS programming. Below line of code:
button.setTitle("myTitle", forState: UIControlState.Normal)
only applies to IBOutlets
, not IBActions
.
So, if your app is using a button as a function to execute some code, say playing music, and you want to change the title from Play
to Pause
based on a toggle variable, you need to also create an IBOutlet
for that button.
If you try to use button.setTitle
against an IBAction
you will get an error. Its obvious once you know it, but for the noobs (we all were) this is a helpful tip.