How to put an image in the center of navigationBar of a UIViewController?

后端 未结 7 2155
耶瑟儿~
耶瑟儿~ 2021-02-01 05:31

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.



        
相关标签:
7条回答
  • 2021-02-01 06:18
    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.

    0 讨论(0)
提交回复
热议问题