Search code examples
iosobjective-cuiwindow

why xcode single view template don't need to set rootviewcontroller?


As far as i know,if we want to show the UIWindow, we need to do following steps:

  1. create UIWindow
  2. load mian.storyboard and instantiate view controller
  3. set the controller to UIWindow's root viewcontroller, then make UIWindow show

which looks like the following code:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //创建窗口对象
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //创建窗口的根控制器,并且赋值
    UIViewController *rootVc = [[UIViewController alloc]init];
    self.window.rootViewController = rootVc;
    //显示窗口
    [self.window makeKeyAndVisible];
    return YES;
}

or init with storyboard

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {


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


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


    UIViewController *vc = [stroyboard instantiateInitialViewController];

    self.window.rootViewController = vc;

    [self.window makeKeyAndVisible];

    return YES;
}

But in the template, i don't see those code, is there something i neglected?


Solution

  • When you choose single view template, some things automatically happens behind the scene.

    • In your IB, the View Controller UI gets the Is Initial View Controller property checked. That means this View Controller is the root view controller.initial view controller

    • Then you see in the above image, your view controller gets an Object ID. This ID is matched with the initialViewController property of your .xml file of the storyboard. If you right-click on your storyboard file and select source code, you will see something like:

      <?xml version="1.0" encoding="UTF-8"?>
      <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB"
      version="3.0" toolsVersion="12118" systemVersion="16F73"
      targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES"
      useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
      
      ...
      ...
      
      </document>
      

    So basically this is how, the template hooks up for the setup that you previously needed to write from the code. Now you don't have to. These are happening behind the scene of the single view template.