Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 394
Fenda Avatar asked Mar 08 '26 15:03

Fenda


1 Answers

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.

like image 50
Gorka Avatar answered Mar 10 '26 03:03

Gorka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!