Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pop specific View Controller in Swift

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?

like image 461
Mahesh Cheliya Avatar asked May 02 '15 15:05

Mahesh Cheliya


People also ask

How do I use pop view controller 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.

How do I dismiss a specific view controller in Swift?

Use unwind segue instead of using RootViewController. Using unwind you can go back to any ViewController. DismissViewController always send the controller out from NavigationController.

How do I present a two view controller in Swift?

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


2 Answers

Try following code:

for controller in self.navigationController!.viewControllers as Array {     if controller.isKind(of: ViewController.self) {         self.navigationController!.popToViewController(controller, animated: true)         break     } } 
like image 179
Mohit Avatar answered Oct 06 '22 11:10

Mohit


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)     }   } } 
like image 42
budiDino Avatar answered Oct 06 '22 11:10

budiDino