Search code examples
swiftxcodeuinavigationbar

How center a Navigation Bar Image [Swift]


in my project I have a Navigation Bar with a Button to open a slide menu. Now I am trying to set a title image instead of the title string. Unlikely the image is pushed slightly to the right instead of being centered. I thought its because of the slide menu button in the left corner of my navigation bar. If I set a title in main.storyboard everything look properly. Why is it so, that my image won't be centered.

Image function:

func addNavBarImage() {

    let navController = navigationController!

    let image = UIImage(named: "TransparentLogo")
    let imageView = UIImageView(image: image)

    let bannerWidth = navController.navigationBar.frame.size.width
    let bannerHeight = navController.navigationBar.frame.size.height

    let bannerX = bannerWidth - image!.size.width
    let bannerY = bannerHeight - image!.size.height
    imageView.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
    imageView.contentMode = .scaleAspectFit

    navigationItem.titleView = imageView
}

Button function:

func addSlideMenuButton(){
    let btnShowMenu = UIButton(type: UIButton.ButtonType.system)
    btnShowMenu.setImage(self.defaultMenuImage(), for: UIControl.State())
    btnShowMenu.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
    btnShowMenu.addTarget(self, action: #selector(BaseViewController.onSlideMenuButtonPressed(_:)), for: UIControl.Event.touchUpInside)
    btnShowMenu.tintColor = UIColor(red: 3, green: 49, blue: 79)
    let customBarItem = UIBarButtonItem(customView: btnShowMenu)
    self.navigationItem.leftBarButtonItem = customBarItem;

}

Solution

  • Change the frame of your titleView in func addNavBarImage() like this:-

    func addNavBarImage() {
    
    let navController = navigationController!
    
    let image = UIImage(named: "TransparentLogo")
    let imageView = UIImageView(image: image)
    
    let bannerWidth = navController.navigationBar.frame.size.width
    let bannerHeight = navController.navigationBar.frame.size.height
    
    let bannerX = bannerWidth - image!.size.width
    let bannerY = bannerHeight - image!.size.height
    imageView.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
    imageView.contentMode = .scaleAspectFit
    
    navigationItem.titleView = imageView
    }
    

    to this

    func addNavBarImage() {
    let imageView = UIImageView(image: #imageLiteral(resourceName: "TransparentLogo"))
    imageView.frame = CGRect(x: 0, y: 0, width: 170, height: 30)
    imageView.contentMode = .scaleAspectFit
    
    let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 170, height: 30))
    
    titleView.addSubview(imageView)
    titleView.backgroundColor = .clear
    self.navigationItem.titleView = titleView
    }