Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Black screen when programmatically creating navigation controller

I am programmatically creating a navigation controller like so:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.mainMenuViewController = [[MainMenuViewController alloc] init];
    self.window.rootViewController = self.mainMenuViewController;
    UINavigationController* navigationController = [[UINavigationController alloc] initWithRootViewController:self.window.rootViewController];
    [self.window makeKeyAndVisible];
    [[GKHelper sharedInstance] authenticateLocalPlayer];
    return YES;
}

And, while Xcode seems perfectly happy with this, I am getting a black screen when I launch my app with this code. When I comment it out, and just user the arrow in the storyboard it works fine but I don't get a navigation controller. What am I doing wrong?

like image 687
Logan Shire Avatar asked Jun 03 '13 00:06

Logan Shire


1 Answers

You need to create the UIWindow object before you try to send it messages. You also need to set your navigation controller as the window's rootViewController.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.mainMenuViewController = [[MainMenuViewController alloc] init];
    UINavigationController* navigationController = [[UINavigationController alloc] initWithRootViewController:self.mainMenuViewController];
    self.window.rootViewController = navigationController;
    [self.window makeKeyAndVisible];
    [[GKHelper sharedInstance] authenticateLocalPlayer];
    return YES;
}

UPDATE

I see that you are trying to transition from using a storyboard. Your MainMenuViewController needs to create or load its view somehow. When you were using a storyboard, your MainMenuViewController was loading its view from the storyboard. You have three options:

  1. You can load the MainMenuViewController from the storyboard, so that it loads its view from the storyboard. In the storyboard, give your MainMenuViewController an identifier. Let's say you set the identifier to MainMenu. Then you can load the MainMenuViewController from the storyboard like this:

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    self.mainMenuViewController = [storyboard instantiateViewControllerWithIdentifier:@"MainMenu"];
    
  2. You can create a .xib file containing the view for MainMenuViewController. If you name it MainMenuViewController.xib, the MainMenuViewController will use it automatically (when you're not loading the view controller from the storyboard).

  3. You can implement -[MainMenuViewController loadView] to create the view and store it in self.view.

like image 71
rob mayoff Avatar answered Nov 08 '22 16:11

rob mayoff