UIButton title resets to XIB value

Consider this:


class MyViewController : UIViewController {
  @IBOutlet var myButton: UIButton!
  @IBOutlet var myLabel: UILabel!

  override func viewDidLoad () {
    super.viewDidLoad ()
    myButton.setTitle("New button text", forState: [.Normal, .Selected, .Highlighted, .Disabled, .Focused])
    myLabel.text = "New label text"
  }
}


Both myLabel and myButton have placeholder text values in .storyboard file: "Old label text" and "Old button text"


Contrary to my expectation this is what I get when the view appears: "New label text" and "Old button text". Any idea why?


The button is a plain button with plain title (not an attributed title). If it helps, this is happening in iOS Action Extension, when the view controller appears in another app.

Replies

This is what fixed it for me:

myButton.setTitle("New button text", forState: .Normal)


i.e. I had to use only .Normal control state, not the list of all states. Still interested in explanation.

You may be correct but I think that viewDidLoad occurs before the XIB sets its default values.

The better place to put this code is in viewWillAppear

and all you most likely care about is UIControlStateNormal.