I used the Objective-C
code below to pop a specific ViewController
.
for (UIViewController *controller in self.navigationController.viewControllers) { if ([controller isKindOfClass:[AnOldViewController class]]) { //Do not forget to import AnOldViewController.h [self.navigationController popToViewController:controller animated:YES]; break; } }
How can I do that in Swift?
You can do it by selecting the View Controller in Storyboard editor and clicking Editor -> Embed In -> Navigation Controller. Also make sure that you have your Storyboard Entry Point (the arrow that indicates which view controller is presented first) either pointing to Navigation Controller or before it.
Use unwind segue instead of using RootViewController. Using unwind you can go back to any ViewController. DismissViewController always send the controller out from NavigationController.
For solving this, you will need to do a pretty simple trick which is to take a screenshot from the first view controller and passing it to the second view controller to display it while presenting the third view controller. You can check this repository to see how it is exactly could be done (Swift 3).
Try following code:
for controller in self.navigationController!.viewControllers as Array { if controller.isKind(of: ViewController.self) { self.navigationController!.popToViewController(controller, animated: true) break } }
Swift 5
To pop to the latest instance of a specific class, for example SomeViewController
:
navigationController?.popToViewController(ofClass: SomeViewController.self)
But you need to add ths UINavigationController
extension:
extension UINavigationController { func popToViewController(ofClass: AnyClass, animated: Bool = true) { if let vc = viewControllers.last(where: { $0.isKind(of: ofClass) }) { popToViewController(vc, animated: animated) } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With