问题
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