frank frank - 7 months ago 9
Swift Question

How do I get back to root view from any current views when click back button using swift?

I want to get back to the root view whenever I click the top left "back" button at any current view.

I found

popToRootViewControllerAnimated
may help, but I don't know how to use it, where to add that in a view class.

and maybe I can use the below function?

func popToRootViewControllerAnimated(_ animated: Bool) -> [UIViewController]?


But how do I use this in case of I click the back button?

Answer

As explained in the official documents "Pushing and popping stack items"

func popToRootViewControllerAnimated(_ animated: Bool) -> [UIViewController]?

Pops all the view controllers on the stack except the root view controller and updates the display.

You can use it simply with:

@IBAction func backToRootButton(sender: UIButton) {
        navigationController?.popToRootViewControllerAnimated(true)
}

This image can explain when you need to go to rootViewController: enter image description here

With this code below you can customize your navigationController back button:

    override func viewDidLoad {
            super.viewDidLoad()
            self.navigationItem.hidesBackButton = true
            let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Bordered, target: self, action: "back:")
            self.navigationItem.leftBarButtonItem = newBackButton;
        }

        func back(sender: UIBarButtonItem) {
            // Perform your custom actions
            // ...
            // Go back to the previous ViewController
            //self.navigationController?.popViewControllerAnimated(true)
            // ..or go back to the rootViewController             
     self.navigationController?.popToRootViewControllerAnimated(true)
        }

You decide if you need to simply pop to the previous viewController or go directly to the root, depend how deep is your stack or who are you topViewController in this moment..