1

I want to be able to change the action of the back bar button item on a specific UIViewController in my navigation controller so that it pops to the root view controller. I've tried the following but they don't work:

let backButton = UIBarButtonItem(title: nil, style: .plain, target: self, action: #selector(back))
self.navigationItem.backBarButtonItem = backButton

and

self.navigationItem.backBarButtonItem?.action = #selector(back)

Any suggestions?

Tometoyou
  • 7,792
  • 12
  • 62
  • 108

4 Answers4

1

You should use self.navigationItem.leftBarButtonItem = backButton

Good luck

Tarek A.
  • 218
  • 2
  • 12
1

First of all backBarButtonItem action not works because you can only change back button title,take a look question about it here.

Solution

In ViewController from which you want to pop to root ViewController you need to set as a delegate of UINavigationControllerDelegate

override func viewDidLoad() {
    super.viewDidLoad()
    
     navigationController?.delegate = self
}

and implement UINavigationControllerDelegate this method`

func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
    if viewController.isKind(of:PreviousViewController.self) {
        navigationController.popToRootViewController(animated: animated)
    }
}

If my answer not fit your needs you can check similar question here.

Community
  • 1
  • 1
Vardan
  • 61
  • 1
  • 6
0

To keep the same look and feel of the back button but change the action, see the ViewWillDisappear answer to the question regarding, "Execute action when back bar button of UINavigationController is pressed" Execute action when back bar button of UINavigationController is pressed

Steve Robertson
  • 209
  • 5
  • 12
-2

This is your solution, just need to set target and selector, nothing more.

 private func setNavBar() {
    let item = navigationItem.backBarButtonItem
    item?.target = self
    item?.action = #selector(self.donePressed)
    navigationItem.leftBarButtonItem = item
}

 @objc private func donePressed() {
    self.dismiss(animated: true, completion: nil)
}
MMDev11070
  • 131
  • 5