1

I am having troubles setting the self.navigationItem.titleView, could someone please help me catch my mistake.

import Foundation

class CustomNavigationController: UINavigationController
{
    override func viewDidLoad() {
        let logo = UIImage(named: "browse_back")
        var hexColor = 0x21BBD4 as UInt
        self.navigationBar.barTintColor = GeneralHelper.UIColorFromRGB(hexColor)
        self.navigationItem.titleView = UIImageView(image: logo)
    }
}

Here is my code for setting the titleView to an image.

enter image description here enter image description here

When I run the application, the color of the navigation bar is being changed to the correct color, but the titleView image is not displaying.

  • I've tested to ensure the image does exist.

Thanks.

2 Answers 2

9

The managing UINavigationController object uses the navigation items of the topmost two view controllers to populate the navigation bar with content.

Source: UINavigationItem Class Reference

You have to set the titleView of the navigationItem of the controller that is the top most controller in the navigation stack managed by your custom navigation controller.

Sign up to request clarification or add additional context in comments.

3 Comments

Ah so, this would mean aI wouldn't get setting it in the Navigation Controller, but the first controller in the navigation controller stack? Edit: Worked. Sweet thanks for the help, I will it mark it as the answer.
Yes, exactly. You set it in the controller that is pushed on the stack.
Also try specifying a size for the Frame of the UIView you add.
6

For those using a UILabel as your titleView

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    navigationItem.titleView?.sizeToFit()
}

Hope this works!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.