Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset root view controller

Tags:

ios

swift

Is it possible to reset the root view controller? With reset I mean resetting it to its initial state so viewDidLoad will be called again. I'm using a UITabBarController and when I logout I want all the tabs previously loaded to be unloaded.

like image 973
Daniel Tovesson Avatar asked Mar 09 '23 12:03

Daniel Tovesson


2 Answers

You can do this by setting the instance of TabBarController to rootViewController on logout action.

Swift 3:

let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let tabBarController = storyBoard.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController
UIApplication.shared.keyWindow?.rootViewController = tabBarController
UIApplication.shared.keyWindow?.makeKeyAndVisible()

Objective C:

UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UITabBarController *tabBarController = [storyBoard instantiateViewControllerWithIdentifier:@"TabBarController"];
[[[UIApplication sharedApplication] keyWindow] setRootViewController:tabBarController];
[[[UIApplication sharedApplication] keyWindow] makeKeyAndVisible];
like image 138
Rahul Kumar Avatar answered Mar 19 '23 08:03

Rahul Kumar


If you are using navigation controller on Tabbarcontroller then navigate to that navigation controller otherwise go to Tabbarcontroller as-

 let appDelegate = UIApplication.shared.delegate as! AppDelegate
 let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
 let tabBar = mainStoryboard.instantiateViewControllerWithIdentifier("TabBarController") as! TabBarController
 appDelegate.window?.rootViewController = tabBar
 appDelegate.window?.makeKeyAndVisible()
like image 22
Jack Avatar answered Mar 19 '23 08:03

Jack