问题
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?
回答1:
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;
}
}
回答2:
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.
回答3:
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)
回答4:
for viewController in (self.navigationController?.viewControllers)! {
if(viewController is YourViewController) {
self.navigationController?.popToViewController(viewController, animated: true)
break;
}
}
I solved it like this.
来源:https://stackoverflow.com/questions/31878108/ios-swift-poptoviewcontroller-by-name