2

I'm trying to pop to a viewcontroller which I believe is at index 0. My ViewController name is HomeVC.

 self.navigationController!.popToViewController(self.navigationController!.viewControllers[0] as! UIViewController, animated: true)

However, the code above only pops me back to the most recent viewcontroller. Not sure why it's not going to my HomeVC viewcontroller. Is their a way I can use the ViewController Name to pop to it?

SlopTonio
  • 1,105
  • 1
  • 16
  • 39
  • Explained here: http://stackoverflow.com/questions/30003814/how-can-i-pop-specific-view-controller-in-swift/40314079#40314079 – PabloR Oct 28 '16 at 22:34

4 Answers4

12

Try this:

for (var i = 0; i < self.navigationController?.viewControllers.count; i++) {
    if(self.navigationController?.viewControllers[i].isKindOfClass(YourDesiredViewController) == true) {
           self.navigationController?.popToViewController(self.navigationController!.viewControllers[i] as! DestinationViewController, animated: true)   
           break;
    }
}
mohamedrias
  • 18,326
  • 2
  • 38
  • 47
iAnurag
  • 9,286
  • 3
  • 31
  • 48
0

You can use popToRootViewControllerAnimated to pop to the View controller at index zero.

It returns an array of view controllers that were popped, that might help you in debugging the issue.

toofani
  • 1,650
  • 13
  • 16
  • I've used the popToRoot and it takes me back to my most recent viewcontroller. Is their a way I can just specify the name of the viewcontroller? – SlopTonio Aug 07 '15 at 12:54
0

Add following UINavigationController extension

extension UINavigationController {

    func popToClass<T: UIViewController>(type: T.Type) -> Bool {
        for viewController in self.viewControllers {
            guard let _ = viewController as? T else { continue }
            self.popToViewController(viewController, animated: true)
            return true
        }
        return false
    }

}

Use as follows

let success = navigationController.popToClass(MyVC.self)
Jože Ws
  • 1,754
  • 17
  • 12
0
    for viewController in (self.navigationController?.viewControllers)! {
        if(viewController is YourViewController) {
            self.navigationController?.popToViewController(viewController, animated: true)
            break;
        }
    }

I solved it like this.