Search code examples
iphonexcode4subviewmainwindow

SubView did not load in the first launching of my application


I'm new to iPhone development. I tried to build a simple application with a window and a navigation controller as a sub-view of this window. The problem is this: the sub view did not load when I launch the application. I just have a windows with black screen. To load the view controller, I have to quit the application and launch it a second time, then I have my sub view with the navigation controller. I added a button directly in the window to make sure that the black screen is not a problem, but I saw the button at startup.

This is the code I have in my AppDelegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]autorelease];
    [self.window addSubview:_navigationController.view]; 
    [self.window makeKeyAndVisible];    
    return YES;
}

Do you have any solution for this problem?

Thank you.


Solution

  • You need to make sure that you have your view hierarchy setup. The window's rootViewController will be the UINavigationController. The UINavigationController controls a hierarchy of viewControllers, so when you instantiate it, you need to assign a rootViewController. Often times this is a subclass of a UITableView.

    Because you are alloc/initing the window, I'm assuming that you do not have a XIB/NIB with the UINavigationController and an associated rootViewController like a UITableViewController. Also, rather than adding the view of your navigation controller, you need to assign the rootViewController, to the window. Since iOS4 this is the preferred way of doing things. See here as well. Try this code:

    YourViewController *yourViewController = /* code for alloc/initing your viewController */
    _navigationController=[[UINavigationController alloc] initWithRootViewController:yourViewController ]
    self.window.rootViewController=_navigationController; /* instead of using [self.window addSubview: _navigationController.view] */
    [self.window makeKeyAndVisible];
    

    If you are using a XIB/NIB, then you need to make sure the _navigationController is wired up to the XIB file and has a subclass of a viewController wired up as it's rootViewController.

    Good Luck