I have a long View Controllers hierarchy;
in the first View Controller I use this code:
SecondViewController *svc = [[SecondViewController alloc] i
The problem with most solutions is that when you dismiss the stack of presented viewControllers, the user will briefly see the first presented viewController in the stack as it is being dismissed. Jakub's excellent solution solves that. Here is an extension based on his answer.
extension UIViewController {
func dismissAll(animated: Bool, completion: (() -> Void)? = nil) {
if let optionalWindow = UIApplication.shared.delegate?.window, let window = optionalWindow, let rootViewController = window.rootViewController, let presentedViewController = rootViewController.presentedViewController {
if let snapshotView = window.snapshotView(afterScreenUpdates: false) {
presentedViewController.view.addSubview(snapshotView)
presentedViewController.modalTransitionStyle = .coverVertical
}
if !isBeingDismissed {
rootViewController.dismiss(animated: animated, completion: completion)
}
}
}
}
Usage: Call this extension function from any presented viewController that you want to dismiss back to the root.
@IBAction func close() {
dismissAll(animated: true)
}