Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting Storyboard on Logout

I am building an IOS 5.1 web client app that uses a storyboard. One of my actions is "logout", during which I want to reset my root view to the initial view created by the root view of the Storyboard. (When you log in, some view items are removed or added based on who you are; when you log out, I want to reset them to their default values, which I've specified in the storyboard.)

I realize that I could programmatically reset/re-add all of the elements, but then what good is the storyboard? I figure there's got to be a way to get back to square one by reloading the view file, right?

like image 818
Jason Avatar asked Apr 23 '12 01:04

Jason


2 Answers

I found the following approach works for me. Please note that I use ARC, unsure if this has much bearing on the solution however. First, in the app delegate class, in application:didFinishLaunchingWithOptions: I capture the inital Storyboard instance with the following line of code:

_initalStoryboard = self.window.rootViewController.storyboard;

(Obviously there is an instance variable UIStoryboard* _initalStoryboard;)

Then I have the following function defined in my app delegate:

- (void)resetWindowToInitialView
{
    for (UIView* view in self.window.subviews)
    {
        [view removeFromSuperview];
    }

    UIViewController* initialScene = [_initalStoryboard instantiateInitialViewController];
    self.window.rootViewController = initialScene;
}

Please note the for in loop which removes all subviews from window. The UIWindow rootViewController documentation states:

If the window has an existing view hierarchy, the old views are removed before the new ones are installed.

However I did not find this to be the case... so I remove the existing views myself explicitly before assigning a new rootViewController. I have not found any worrying side effects or memory leaks using this method. I am by no means an expert on the magic of UIKit so I would suggest you test test and retest this solution if you plan to use it yourself. Cheers

like image 72
Herr Grumps Avatar answered Nov 12 '22 09:11

Herr Grumps


The following works great for me, if you use a NavController-based structure:

UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
UINavigationController *navController = (UINavigationController *)window.rootViewController;
UIViewController *vc = [navController.storyboard instantiateViewControllerWithIdentifier:@"Login"];
navController.viewControllers = @[vc];

You have to assign the Storyboard ID "Login" to your Login VC in order for this to work.

like image 31
thgc Avatar answered Nov 12 '22 09:11

thgc