iosswift3uinavigationcontrollerpoptoviewcontroller

Swift 3: popToViewController not working


In my app I have three table view controllers and then potentially many UIViewControllers each of which has to lead back to the first table view controller if the user presses back at any point. I don't want the user to have to back through potentially hundreds of pages. This is what I amusing to determine if the user pressed the back button and it works the message is printed

override func viewWillDisappear(_ animated: Bool) {
    if !movingForward {
        print("moving back")
        let startvc = self.storyboard!.instantiateViewController(withIdentifier: "FirstTableViewController")
        _ = self.navigationController!.popToViewController(startvc, animated: true)
    }
}

I have searched and none of the solutions have worked so far.


Solution

  • popToViewController not work in a way you are trying you are passing a complete new reference of FirstTableViewController instead of the one that is in the navigation stack. So you need to loop through the navigationController?.viewControllers and find the FirstTableViewController and then call popToViewController with that instance of FirstTableViewController.

    for vc in (self.navigationController?.viewControllers ?? []) {
        if vc is FirstTableViewController {
            _ = self.navigationController?.popToViewController(vc, animated: true)
            break
        }
    }
    

    If you want to move to First Screen then you probably looking for popToRootViewController instead of popToViewController.

    _ = self.navigationController?.popToRootViewController(animated: true)