How to center an image in navigationBar across all UIViewControllers? Swift / Obj-C

I have faced the same issue. Then i tried one code shown below.

 override func viewDidAppear(animated: Bool) {

    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 150, height: 40))
    imageView.contentMode = .ScaleAspectFit

    let image = UIImage(named: "googlePlus")
    imageView.image = image

    navigationItem.titleView = imageView
  }

This Code working fine when i tested with Left & Right Bar Button.

But in my previous code there is no Right Bar Button.

So the image is moving towards right.

For solving this i created a Right Bar Button & change the Tint color to clear color.

So everything seems to be working fine. This is one Temporary Solution for your problem.


The easiest way of doing this is in Interface Builder.

Simply drag a 'NavigationItem' from the object library and place it into your ViewController, then place a UIView where the title goes (ensure you set the background to 'clear') Then place a UIImageView into that view and set the image in the Attributes Inspector to your required image. Scale your UIImage accordingly and set your your constraints accordingly.


I created an extension for solving this problem using the hint of @idrougge.

In order to center the title view image no matter what buttons you have, a content view is set as title view, then the image view is added as child of the content view. Finally, using constraints the image view is aligned inside its parent (content view).

import UIKit

extension UIViewController {

    func addLogoToNavigationBarItem() {
        let imageView = UIImageView()
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.heightAnchor.constraint(equalToConstant: <your_height>).isActive = true
        imageView.contentMode = .scaleAspectFit
        imageView.image = <your_image>
        //imageView.backgroundColor = .lightGray

        // In order to center the title view image no matter what buttons there are, do not set the
        // image view as title view, because it doesn't work. If there is only one button, the image
        // will not be aligned. Instead, a content view is set as title view, then the image view is
        // added as child of the content view. Finally, using constraints the image view is aligned
        // inside its parent.
        let contentView = UIView()
        self.navigationItem.titleView = contentView
        self.navigationItem.titleView?.addSubview(imageView)
        imageView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
        imageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
    }
}

I hope this helps someone,

Xavi

Tags:

Ios

Swift