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

后端 未结 7 2151
耶瑟儿~
耶瑟儿~ 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:07

    func centeredNavBarImage (){
        let navcontroller = navigationController!
        let image = #imageLiteral(resourceName: "yourImage")
        let imageView = UIImageView(image:image)
    
        let bannerWidth = navcontroller.navigationItem.accessibilityFrame.size.width
        let bannerHeight = navcontroller.navigationBar.frame.size.height
    
    
        let bannerX = bannerWidth / 2 - image.size.width / 2
        let bannerY = bannerHeight / 2 - image.size.height / 2
    
        imageView.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
        imageView.contentMode = .scaleAspectFit
    
        navigationItem.titleView = imageView
    
    }
    

    This is a modified code from https://youtu.be/bLkuu_fmlsU

    The bannerWidth takes into account a refresh button item I have on the right side of the navbar. Seems to work.

    Run the function on ViewDidLoad

提交回复
热议问题