Search code examples
iosswiftuinavigationcontrollerback-button

backBarButtonItem image right aligned, want centered


I'm trying to set the backBarButtonItem to have a custom image:

self.navigationItem.backBarButtonItem = UIBarButtonItem(image: UIImage(named: "Back"), style: .plain, target: self, action: #selector(self.navigationController?.popViewController(animated:)))
self.navigationItem.backBarButtonItem?.tintColor = UIColor.red

I'm noticing that when I set the backBarButtonItem for my navigationController the image gets right aligned within the backBarButtonItem's frame:

enter image description here

enter image description here

What can I do to make the image centered, or even left aligned?


Solution

  • Instead of backBarButtonItem you need to set leftBarButtonItem

    Replace this

    self.navigationItem.backBarButtonItem = UIBarButtonItem(image: UIImage(named: "Back"), style: .plain, target: self, action: #selector(self.navigationController?.popViewController(animated:)))
    self.navigationItem.backBarButtonItem?.tintColor = UIColor.red
    

    by this

    self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "Back"), style: .plain, target: self, action: #selector(self.navigationController?.popViewController(animated:)))
    self.navigationItem.leftBarButtonItem?.tintColor = UIColor.red