Programming iOS: clarifications about Root View Controller

后端 未结 4 686
生来不讨喜
生来不讨喜 2020-12-15 11:20

Through this question I would like to know if I understand well the notion of Root View Controller.

In iOS application, the Root View Controller (RVC) is the control

4条回答
  •  抹茶落季
    2020-12-15 11:35

    Ya.. when I began iPhone dev.. the rootViewController thing threw me for a loop too. But it’s really straight forward.

    when the app starts, I create a UIWindow object in my app delegate class. Also, in that class, I have a property of type UIWindow called window;

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
    
        UIWindow *w = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
        self.window=w;
        [w release];
        // other code here...
    }
    

    I then create a UIViewController whose view will be the first view in the window hierarchy, this could be called the "root view controller".

    The confusing part is...that often we create a UINavigationController as the "root view controller" and that navigation controller has an init method that asks for a "RootViewController", which is the first viewcontroller it will place on its stack.

    So, the window gets a "root view controller", which is the UINavigationController, which also has a RootViewController, which is the first view controller you want to show.

    once you sort that out, its all makes sense.. I think :-)

    here is some code that does it all.. (taken from a project I have open in front of me)

    //called with the app first loads and runs.. does not fire on restarts while that app was in memory
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
    
        //create the base window.. an ios thing
        UIWindow *w = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
        self.window=w;
        [w release];
    
        // this is the home page from the user's perspective
        //the UINavController wraps around the MainViewController, or better said, the MainViewController is the root view controller
        MainViewController *vc = [[MainViewController alloc]init];
    
        UINavigationController *nc = [[UINavigationController alloc]initWithRootViewController:vc];
        self.navigationController=nc;  // I have a property on the app delegate that references the root view controller, which is my navigation controller.
    
        [nc release];
        [vc release];
    
        //show them
        [self.window addSubview:nc.view];
        [self.window makeKeyAndVisible];
    
        return YES;
    }
    

提交回复
热议问题