How to dismiss 2 view controllers in Swift iOS?
Below is my code.
@IBAction func backButtonTapped(sender: AnyObject) {
self.presentingViewController
.presentingViewController
.dismissViewControllerAnimated(true, completion: nil)
}
Swift 3+ version. You can dismiss two view controllers at a time in Swift 3 with this below code.
func dismissTwoViews() {
self.presentingViewController?
.presentingViewController?.dismiss(animated: true, completion: nil)
}
Swift 4+ version. just we need pop particular view controller use this extension
extension UINavigationController {
func popToViewController(ofClass: AnyClass, animated: Bool = true) {
if let vc = viewControllers.filter({$0.isKind(of: ofClass)}).last {
popToViewController(vc, animated: animated)
}
}
func popViewControllers(viewsToPop: Int, animated: Bool = true) {
if viewControllers.count > viewsToPop {
let vc = viewControllers[viewControllers.count - viewsToPop - 1]
popToViewController(vc, animated: animated)
}
}
}
And use like this in your view controller class
for controller in self.navigationController!.viewControllers as
Array {
if controller.isKind(of:
yourPopControllerName.self) {
self.navigationController?.isNavigationBarHidden = false
_ =
self.navigationController!.popToViewController(controller,
animated: false)
break
}
}