Search code examples
iosuiviewcontrolleruistoryboardappdelegatepushviewcontroller

iOS ViewController doesn't appears although viewDidLoad gets called


I'm building an application with different states that need to be restored if a user quits the app for some reason. This means, that different screens/viewcontrollers need to be on top of the navigation stack when the app launching. To achieve this, I tried to build the viewcontrollers programatically, see below:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        switch (appState)
        {
            case CSAppStateIdle:
            {
                //replace and push rootview manually
                MainVC* mainView = [storyboard instantiateViewControllerWithIdentifier:@"MainVC"];
                [(UINavigationController *)self.window.rootViewController pushViewController:mainView animated:YES];
            }
                break;
            case CSAppStateSomeState:
            {
                MainVC* mainView = [storyboard instantiateViewControllerWithIdentifier:@"MainVC"];
                SomeVC* someView = [storyboard instantiateViewControllerWithIdentifier:@"SomeVC"];
                [(UINavigationController *)self.window.rootViewController addChildViewController:mainView];
                [(UINavigationController *)self.window.rootViewController pushViewController:someView animated:YES];
            }
                break;

            default:
                break;
        }

I use stroyboards with ID-s set correctly. Well in CSAppStateIdle it works, but in CSAppStateSomeState someView doesn't appear on screen, but in someVC viewDidLoad, viewWillAppear and even viewDidAppear gets called.

Has anyone faced this before, or knows the solution? I appreciate any help, thanks!


Solution

  • To put both items on the navigation stack, use the setViewControllers:animated: method, passing an array with both items:

            case CSAppStateSomeState:
            {
                MainVC* mainView = [storyboard instantiateViewControllerWithIdentifier:@"MainVC"];
                SomeVC* someView = [storyboard instantiateViewControllerWithIdentifier:@"SomeVC"];
                [(UINavigationController *)self.window.rootViewController setViewControllers:@[mainView, someView] animated:YES];
            }