Open your storyboard and view controller source side by side in the assistant editor. Then select the label. Switch to the connections inspector and then drag from the small circle next to "New Referencing Outlet" and into the view controller source file. This should create the @IBOutlet for you.
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.
Swift 5.0
// Standard State
myButton.setTitle("Title", for: .normal)
let controlStates: Array<UIControl.State> = [.normal, .highlighted, .disabled, .selected, .focused, .application, .reserved]
for controlState in controlStates {
button.setTitle(NSLocalizedString("Title", comment: ""), for: controlState)
}
Swift 3:
Set button title:
//for normal state:
my_btn.setTitle("Button Title", for: .normal)
// For highlighted state:
my_btn.setTitle("Button Title2", for: .highlighted)
Changing title when attributed is a bit different :
I just ran into a problem : If you have an UIButton with an Attributed Title, you have to use :
my_btn.setAttributedTitle(NSAttributedString(string: my_title), for: my_state)
as, per Apple SetTitle Doc :
If you set both a title and an attributed title for the button, the button prefers the use of the attributed title over this one.
I had an attributed title and I tried to setTitle on it, with no effect...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With