3

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.

4

3 回答 3

14

popToViewController无法以您尝试的方式工作您正在传递一个完整的新引用,FirstTableViewController而不是导航堆栈中的引用。因此,您需要遍历navigationController?.viewControllers并找到FirstTableViewController,然后popToViewController使用该实例调用FirstTableViewController.

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

如果您想移至第一个屏幕,那么您可能正在寻找popToRootViewController而不是popToViewController.

_ = self.navigationController?.popToRootViewController(animated: true)
于 2017-04-21T09:38:13.467 回答
1

尝试这个 :

let allViewController: [UIViewController] = self.navigationController!.viewControllers as [UIViewController];

                        for aviewcontroller : UIViewController in allViewController
                        {
                            if aviewcontroller .isKindOfClass(YourDestinationViewControllerName)// change with your class
                            {
                             self.navigationController?.popToViewController(aviewcontroller, animated: true)
                            }
                        }
于 2017-04-21T09:41:53.963 回答
-1

如果您处于回调中,尤其是异步网络回调中,您可能不在主线程上。如果这是你的问题,解决方案是:

DispatchQueue.main.async {
    self.navigationController?.popToViewController(startvc, animated: true)
}

系统调用viewWillDisappear()总是在主线程上调用。

于 2019-03-05T19:14:58.900 回答