AK1 AK1 - 3 months ago 7
Objective-C Question

Initializing a view controller as a initial view controller while using navigational controller ?[Objective-C]

I have tried using navigation view controller and setting up my screen as initial view controller using storyboard and it went well.

But when I did everything programmatically like below in my appDelegate.m file :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.


UIStoryboard *storyboard = [UIStoryboard storyboardWithName: @"Main" bundle:nil];

FirstViewController *firstVC = [storyboard instantiateViewControllerWithIdentifier:@"FirstViewController"];


UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: firstVC];


self.window =[[[UIApplication sharedApplication]delegate] window];

self.window.rootViewController = navController;

return YES;
}



  • My screen on the simulator is blank.

  • But when I checked the
    is initial view controller
    for the respective view controller in the storyboard and run. This time, it worked, and the expected screen is displayed.



My question is, why should I check the
is initial view controller
in the storyboard when I am doing everything programmatically ?.

Thank you.

Rob Rob
Answer

If you're going to create the first view controller yourself in didFinishLaunchingWithOptions, you have to instantiate the UIWindow, too. But your assignment of self.window is just retrieving itself (lol) and does nothing. You'd generally do something like:

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

When you use the "initial view controller" option, it takes care of all of this for you, which is why that works when you check that option.

And don't forget to makeKeyAndVisible:

[self.window makeKeyAndVisible];

Thus:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *firstVC = [storyboard instantiateViewControllerWithIdentifier:@"FirstViewController"];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: firstVC];

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = navController;
    [self.window makeKeyAndVisible];

    return YES;
}
Comments