How to use image logo in navigation bar instead of title

I tried a couple of different codes, but could not make the logo display

import UIKit 
class HomeViewController: UIViewController { 

override func viewDidLoad() { 
super.viewDidLoad() 

let logo = UIImage(named: "logo.png") 
let imageView = UIImageView(image: logo) 
self.navigationItem.titleView = imageView
navigationItem.titleView?.sizeToFit() 
 } 
}

I even tried to include IB in the class itself, it also did not work, it seems that this is not so.

@IBOutlet weak var navBar: UINavigationItem!

PS. My logo is 200x40px png and its name is logo.png in assets.

My storyboard

http://i68.tinypic.com/b68t8o.png

Any help is appreciated

Edit: I solved my problem by putting in its place the entire view of the navigation history. Thanks for your suggestions.

+4
source share
3 answers

try it

 let logo = UIImage(named: "logo.png") 
 let imageView = UIImageView(image: logo) 
 imageView.contentMode = .ScaleAspectFit // set imageview content mode
 self.navigationItem.titleView = imageView 

or add it below

 let logo = UIImage(named: "logo.png") 
 let imageView = UIImageView(image: logo) 
 imageView.contentMode = .ScaleAspectFit // set imageview content mode
 self.navBar.topItem?.titleView = imageView
+9
source

Set the image content mode, for example,

 imageView.contentMode = .ScaleAspectFit
0

This code looks good, I think there is an error in the name of UIImage, you debugged and checked that the logo is not nil ? try removing ". jpg"

0
source

Source: https://habr.com/ru/post/1656052/


All Articles