I have this snippet of code used in viewDidLoad of a UIViewController. I\'va no errors. Images exists. I get the background but not the image. Image is a sort of logo.
extension UINavigationController {
func addLogoImage(image: UIImage, navItem: UINavigationItem) {
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 44))
view.addSubview(imageView)
navItem.titleView = view
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
imageView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
view.heightAnchor.constraint(equalTo: navigationBar.heightAnchor).isActive = true
view.centerXAnchor.constraint(equalTo: navigationBar.centerXAnchor).isActive = true
view.centerYAnchor.constraint(equalTo: navigationBar.centerYAnchor).isActive = true
}
}
Here's what I'm using.
Of course, you might need a bit more constraints, so as to not clash with the right and left bar button items.