rosst400
rosst400

Reputation: 573

iOS: Conditionally load a view controller

Is there any way to conditionally load a view controller from the App Delegate?

So for example, can this be done?

    if (hasUserSignedUp) {
        nav = [[navController alloc] initWithNibName:nil bundle:nil];
        [window addSubview:nav.view];
        [window makeKeyAndVisible];
    }
    else {
        su = [[SignUpViewController alloc] initWithNibName:nil bundle:nil];
        [window addSubview:su.view];
        [window makeKeyAndVisible];
    }

Upvotes: 2

Views: 1719

Answers (4)

samson
samson

Reputation: 1152

Yes, you certainly can do it that way.

Upvotes: 0

adamgliea
adamgliea

Reputation: 161

set rootViewController is good habit

Upvotes: 0

Ash Furrow
Ash Furrow

Reputation: 12421

While this is certainly possible, what's probably a better idea is to load your navigation controller in both cases and, depending on if they've signed up, use a different root view controller.

if (hasUserSignedUp) {
    nav = [[UINavigationController alloc] initWithRootViewController:rootViewController];
}
else {
    su = [[SignUpViewController alloc] initWithNibName:nil bundle:nil];
    nav = [[UINavigationController alloc] initWithRootViewController:su];
}

[window addSubview:nav.view];
[window makeKeyAndVisible];

The app delete should create the root of the view hierarchy, and from there, you can manipulate it as you see fit.

If I were you, I would use the code above and, once they have signed in or signed up, push the regular root view controller and then modify the nav stack stack:

[self.navigationController pushViewController:rootViewController animated:YES];

double delayInSeconds = 0.5f;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    self.navigationController.viewControllers = [NSArray arrayWithObject:self.navigationController.viewControllers.lastObject];
});

This isn't the cleanest way to do this (dispatch_after), but you see how it's done. Make sure the rootViewController has hidesBackButton set to YES.

Upvotes: 1

Nikita Pestrov
Nikita Pestrov

Reputation: 5966

Yes, it is quite convinient, there are no restrictions for you to do this.

But you'd better set rootViewController instead of adding a view, i think.

self.window.rootViewController = nav;//or su;

Upvotes: 1

Related Questions