Alexander Khitev
Alexander Khitev

Reputation: 6841

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

Upvotes: 1

Views: 713

Answers (2)

adrgrondin
adrgrondin

Reputation: 668

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.

Upvotes: 2

temp_
temp_

Reputation: 1317

Try self.navigationItem.setHidesBackButton(true, animated: true) in viewDidLoad or viewWillAppear. Edit: this hides the native back button. You should be able to then set your own after.

Upvotes: 0

Related Questions