self.window.rootViewController vs window addSubview

IphoneObjective C

Iphone Problem Overview


I've noticed a lot of examples for iPhone apps in the Application Delegate

- (void)applicationDidFinishLaunching:(UIApplication *)application

have

[window addSubview: someController.view]; (1)

as opposed to

self.window.rootViewController = self.someController; (2)

Is there any practical reason to use one over the other? Is one technically correct? Do controller's have an equivalent command to number (2) like

self.someController.rootController = self.someOtherController; // pseudocode

Iphone Solutions


Solution 1 - Iphone

The UIWindow rootViewController property is new with iOS4.

The older technique was to use addSubview.

The new, recommended technique is to set rootViewController.

Solution 2 - Iphone

Just an update on this with the release of ios 6.

If still using the -[UIWindow addsubview:] boilerplate, you will probably get the message "Application windows are expected to have a root view controller at the end of application launch" in your console as well now. Along with potential rotation issues and layout issues in your app.

Setting the window's rootViewController as above will fix this too.

Solution 3 - Iphone

I use this code:

    rootViewController_ = [[RootViewController alloc] initWithFrame:[UIScreen mainScreen].bounds];
    window_ = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    if ([window_ respondsToSelector:@selector(setRootViewController:)]) { // >= ios4.0
        [window_ setRootViewController:rootViewController_];
    } else { // < ios4.0
        [window_ addSubview:rootViewController_.view];
    }

Solution 4 - Iphone

My Opinion:

self.window.rootViewController will resize the rootViewController.view according to status bar height

But if you use addSubview it won't

For example, if you setRootViewController to a NavigationController, the navigationController would be (0,0,320,480);

but if you setRootViewController to a common UIViewController, the navigationController would be (0,0,320,460);

if you use addSubview: the two viewcontrollers would be (0,0,320,480)

And if there is an In-call-StatusBar. it also change for you when you use setRoot... if you use addSubview, the subview size wouldn't change

do some test with different view border color

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGazzerView Question on Stackoverflow
Solution 1 - IphoneTomSwiftView Answer on Stackoverflow
Solution 2 - IphonejaseelderView Answer on Stackoverflow
Solution 3 - IphoneRonView Answer on Stackoverflow
Solution 4 - IphoneaelamView Answer on Stackoverflow