1
votes

I'm trying to add a custom back button to my navigation controller but it doesn't function correctly.

func setupNavBarItems() {
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.view.backgroundColor = UIColor.clear

    let backButton = UIButton(type: .system)
    backButton.setImage(#imageLiteral(resourceName: "icon_back"), for: .normal)
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
}

And I have also tried this without any luck (I replaced the bottom 2 lines with the following code)

    let backButton = UIButton(type: .system)
    backButton.setImage(#imageLiteral(resourceName: "icon_back"), for: .normal)
    let backBarButton = UIBarButtonItem.init(customView: backButton)
    navigationItem.setLeftBarButton(backBarButton, animated: true)

I see the custom button image but the it won't trigger the back button action.

1
you need to perform back action manually, for example self.navigationController.popViewControllerReinier Melian

1 Answers

1
votes

In such cases it's better to declare it as instance variable , as target is being lost with local variables / lazy besides target popViewController

let addButton = UIBarButtonItem(image:UIImage(named:"your_icon_name"), style:.plain, target:self, action:#selector(YourControllerName.buttonAction(_:)))
addButton.tintColor = UIColor.white
self.navigationItem.leftBarButtonItem = addButton

.....

@objc func buttonAction(_ sender: UIBarButtonItem) {
   self.navigationController?.popViewController(animated: true)
 }