Search code examples
iosswiftuinavigationbarback-buttonuinavigationitem

backBarButtonItem display image incorrect


I'm using custom UIBarButtonItem with image for backBarButtonItem. I discovered strange behavior, because in addition to my image, the default Arrow icon is also displayed.

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        navigationItem.backBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "BackButtonIcon"), style: .plain, target: nil, action: nil)
    }

    @IBAction private func push(_ button: UIButton) {
        let secondViewController = SecondViewController()
        navigationController?.pushViewController(secondViewController, animated: true)
    }

}

class SecondViewController: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
    }

}

Result is enter image description here UI debugger


Solution

  • Try to use:

    navigationBar.backIndicatorImage = #imageLiteral(resourceName: "BackButtonIcon")
    
    navigationController?.navigationBar.backIndicatorTransitionMaskImage = #imageLiteral(resourceName: "BackButtonIcon")
    
    navigationItem.backBarButtonItem = UIBarButtonItem(title: "Title", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
    

    The navigation bar have a property for a back image as well as the backItem property which is a UINavigationItem. You can read more here.

    EDIT:

    Use this code in the source view controller not the destination controller.