Goaler444
Goaler444

Reputation: 2621

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
    }

...

}

Upvotes: 5

Views: 6823

Answers (3)

Trey Pringle
Trey Pringle

Reputation: 141

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

Upvotes: 2

Goaler444
Goaler444

Reputation: 2621

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)
    } 
}

Upvotes: 4

nerowolfe
nerowolfe

Reputation: 4817

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);

Upvotes: 0

Related Questions