1

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.popViewController Commented Feb 16, 2018 at 23:55

1 Answer 1

1

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)
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.