3

I'm trying to place a UIButton as the titleView for my UINavigationItem. This is my code but it doesn't work. The title is completely blank.

override func viewDidLoad() {
    super.viewDidLoad()

    let titleButton = UIButton()
    titleButton.titleLabel?.font = UIFont(name: "HelveticaNeue-Medium", size: 16)
    titleButton.titleLabel?.textAlignment = NSTextAlignment.Center;
    titleButton.titleLabel?.text = "My Custom Title"
    titleButton.titleLabel?.sizeToFit()

    self.navigationItem.titleView = titleButton
}

Here is a screenshot of the missing title.

screenshot

Fenda
  • 1,385
  • 3
  • 14
  • 24

2 Answers2

4

If you are using Storyboards, you can drag a UIButton to the titleView. If Interface Builder doesn't let you do it, it's because you need to drag first a UINavigationItem to the navigation bar, so you can then drag views inside, like your UIButton.

Gorka
  • 331
  • 1
  • 5
  • 1
    Oh snap! I didn't know that was even possible. I'm going to accept the other answer as it directly answers what was wrong with the code in the question. However, I am going to go this route because it makes a lot more sense. – Fenda Feb 11 '15 at 15:27
  • I'm glad it helped, @Fenda! Interface Builder is getting more and more powerful time to time, but in silence ;) – Gorka Feb 11 '15 at 15:28
3

To set the title of the button you shouldn't be directly setting the text of the label, you should be configuring the button to set the title for a particular state using func setTitle(_ title: String?, forState state: UIControlState).

Generally you set the title for .Normal and that will then apply to all states (as the default).

Wain
  • 118,658
  • 15
  • 128
  • 151