Swift - How to Dismiss All of View Controllers to Go Back to Root

single function to dismiss all open view controllers

You can call :

self.view.window!.rootViewController?.dismiss(animated: false, completion: nil)

Should dismiss all view controllers above the root view controller.

Swift: Dismissing all view controllers and then presenting a view controller

You can dismiss all viewcontrollers with below code block. In the completion block you can get the topViewController and you can present new viewController over topViewController. I also wrote down an extension for get the topViewController on the window.

UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: true, completion: { [weak self] in
// Get Top Controller With Extension
let topController = UIApplication.topViewController()
// Pressent New Controller over top controller
let congratsPopup = K.mainStoryBoard.instantiateViewController(withIdentifier: "congratsController") as! CongratsController
topController?.present(congratsPopup, animated: true, completion: nil)
})

Get Top View Controller Extension

extension UIApplication {
class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return topViewController(controller: navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController {
if let selected = tabController.selectedViewController {
return topViewController(controller: selected)
}
}
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
}

Back to root view controller in swift

You can just set a new RootController like this:

let storyboard = UIStoryboard(name: "sName", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "<YOUR ROOT CONTROLLER>")
self.window?.rootViewController = viewController

If you don't have a window at self.window you need to instanciate one based on your AppDelegate.

If you're within a NavigationController you can also use the answer of @Anshul Bhatheja

Dismiss all view controllers below current view controller swift

From VC2, use setViewControllers method to push VC3 and to remove the rest,

self.navigationController?.setViewControllers([VC3], animated: true)


Related Topics



Leave a reply



Submit