Swift 3: popToViewController not working

走远了吗. 提交于 2020-01-23 01:35:33

问题


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.


回答1:


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)



回答2:


Try this :

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)
                            }
                        }



回答3:


If you are in a callback, particularly an async network callback, you may not be on the main thread. If that's you're problem, the solution is:

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

The system call viewWillDisappear() is always called on the main thread.



来源:https://stackoverflow.com/questions/43539149/swift-3-poptoviewcontroller-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!