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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With