简体   繁体   中英

How to set an image title in the navigation bar of an iOS app

I am trying to place an image logo as a title within the navigation bar of an iOS app using Swift. I included the image in the assets folder (Images.xcassets). I looked into this question but no luck.

The following is my code:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let logo = UIImage(named: "logo") as UIImage
        let imageView = UIImageView(image:logo)
        imageView.frame.size.width = 200;
        imageView.frame.size.height = 45;

        self.navigationItem.titleView = imageView
    }

...

}

I managed to create a Swift solution. Not sure if its the best way, but it works. I basically translated nerowolfe's code, and used the addSubview function.

class NavigationBar: UINavigationBar {

    init(frame: CGRect) {
        super.init(frame: frame)
        initialise()
    }

    init(coder aDecoder: NSCoder!){
        super.init(coder: aDecoder)
        initialise()
    }

    func initialise(){

        let logo = UIImage(named: "logo");
        let imageView = UIImageView(image:logo)
        imageView.frame.size.width = 145;
        imageView.frame.size.height = 33;
        imageView.frame.origin = CGPoint(x: 2, y: 8)

        addSubview(imageView)
    } 
}

You are just missing a ? when you declare the image, and also may want to add a contentmode:

let logo = UIImage(named: "logo") as UIImage?
    let imageView = UIImageView(image:logo)
    imageView.frame.size.width = 200;
    imageView.frame.size.height = 45;
    imageView.contentMode = UIViewContentMode.ScaleAspectFit

    self.navigationItem.titleView = imageView

Try to use addSubview method to add UIImageView to navigation bar. This is code in Objective-C:

UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-vysk-white"]];
[self.navigationController.navigationBar addSubview:imgView];


imgView.contentMode = UIViewContentModeScaleAspectFit;
imgView.frame = CGRectMake(140, 0, 40, 40);

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