简体   繁体   中英

How to use an image logo on the navigation bar instead of title

I have tried a couple different codes but couldn't make the logo show

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 didn't work either, it doesn't seem to work that way

@IBOutlet weak var navBar: UINavigationItem!

PS. My logo is a 200x40px png and its named logo.png in the assets.

My storyboard

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

Any help is appreciated

Edit: I solved my problem by putting an image view there instead of this whole navigation item story. Thanks for your suggestions though.

try this

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

设置您的图像视图的内容模式,例如,

 imageView.contentMode = .ScaleAspectFit

This code looks good, i think there is error in name of UIImage, did you debug and check that let logo is not nil ? try to remove ".jpg"

Use extension:

extension UIViewController {
    func setNavigationBarLogo() {
        let logo = UIImage(named: "YourLogo.png")
         let imageView = UIImageView(image: logo)
        imageView.contentMode = .scaleAspectFit
         self.navigationItem.titleView = imageView
    }
}

Usage in UIViewController:

 override func viewDidLoad() {
        super.viewDidLoad()
        self.setNavigationBarLogo()
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM