Search code examples
iosswiftuinavigationbar

Adding a logo in Navigation Bar that is left aligned


I have been stumped on how to get an image in a NavigationBar that is left aligned. I understand how to replace the title in the center.

Basically, I have a view controller embedded in a Navigation Bar Controller. In that view controller, I have a search form in the middle and a bar button on the right and I am trying to fit in a logo that is an image to the left side.

Below is the what I understand how to put an image but how do I get it left aligned?

    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
imageView.contentMode = .ScaleAspectFit
let image = UIImage(named: "imageName")
imageView.image = image
navigationItem.titleView = imageView 

Solution

  • You can assign an array of items to the leftBarButtonItems property of the navigationBar. You should add an array because there is usually no space between the left side and the logo, and this doesn't look great. Here is an example:

    func setUpUI() {
        let logoImage = UIImage.init(named: "logoImage")
        let logoImageView = UIImageView.init(image: logoImage)
        logoImageView.frame = CGRectMake(-40, 0, 150, 25)
        logoImageView.contentMode = .ScaleAspectFit
        let imageItem = UIBarButtonItem.init(customView: logoImageView)
        let negativeSpacer = UIBarButtonItem.init(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
        negativeSpacer.width = -25
        navigationItem.leftBarButtonItems = [negativeSpacer, imageItem]
    }
    

    The negative spacer to the left of it will push it over a bit, and you can adjust it from there.