Search code examples
iosxcodeswiftuinavigationcontrollernavigationbar

Adding a title to the left side of the navigation bar


Is it possible to add a title to the left side of the navigation bar? I know how I can add a title in the center but when I try to add one to the left side I see nothing. This is the code I have:

self.navigationItem.leftBarButtonItem?.title = "Elapsed Time: 0:00"

Thank you for the help.


Solution

  • Try this code:

    let leftItem = UIBarButtonItem(title: "Title",
                                       style: UIBarButtonItemStyle.plain,
                                       target: nil,
                                       action: nil)
        leftItem.isEnabled = false
        self.navigationItem.leftBarButtonItem = leftItem
    

    More powerful solution of this problem:

    let longTitleLabel = UILabel()
        longTitleLabel.text = "Long long long long long long title"
        longTitleLabel.font = ................
        longTitleLabel.sizeToFit()
    
        let leftItem = UIBarButtonItem(customView: longTitleLabel)
        self.navigationItem.leftBarButtonItem = leftItem
    

    Now you just can edit label as you want. You can use another font or text color.