Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting titleView of custom UINavigationBar

Tags:

swift

ios8

I have a custom navigation bar that doesn't really do any navigation controlling (app only has one view) its instead used as a header to display the logo against a solid background colour. So I put a navigation bar onto the main view controller and created an outlet so I can reference it in the code. (Using swift by the way).

Right now I'm struggling with setting the logo image in the center of the nav bar. I need to do this with the titleView (instead of setting an entire background image). So far what I've read says to use self.navigationItem.titleView in the view controller, but I think that only works when using a UINavigationController. Here is my code so far:

@IBOutlet weak var navBar: UINavigationBar!

override func viewDidLoad() {
    super.viewDidLoad()

    let logoImage = UIImageView(frame: CGRect(x:0, y:0, width: 200, height: 45))
    logoImage.contentMode = .ScaleAspectFit

    let logo = UIImage(named: "logo.png")
    logoImage.image = logo
    self.navigationItem.titleView = logoImage
}

But this doesn't work. How do I get access to the titleView using a custom UINavigationBar like this?

like image 786
Jonson Bylvaklov Avatar asked Apr 14 '15 04:04

Jonson Bylvaklov


People also ask

How do I change the navigation bar on my iPhone?

A user changes the navigation bar's style, or UIBarStyle , by tapping the “Style” button to the left of the main page. This button opens an action sheet where users can change the background's appearance to default, black-opaque, or black- translucent.

How do I customize the navigation bar in Swift?

Go to the ViewController. swift file and add the ViewDidAppear method. a nav helper variable which saves typing. the Navigation Bar Style is set to black and the tint color is set to yellow, this will change the bar button items to yellow.


1 Answers

You need to access UINavigationBar's topItem attribute. Then you can set the topItem's titleView with a UIImageView.

So in your case:

self.navBar.topItem?.titleView = logoImage
like image 148
Naoto Ida Avatar answered Sep 30 '22 13:09

Naoto Ida