Fenda
Fenda

Reputation: 1385

UIButton as UINavigationItem titleView

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

Upvotes: 3

Views: 699

Answers (2)

Gorka
Gorka

Reputation: 331

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.

Upvotes: 4

Wain
Wain

Reputation: 119031

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).

Upvotes: 3

Related Questions