iOS编程:关于Root View Controller的说明

Lor*_*o B 9 cocoa-touch objective-c ios4 ios rootview

通过这个问题,我想知道我是否理解Root View Controller的概念.

在iOS应用程序中,根视图控制器(RVC)是其视图在启动时添加到UIWindow应用程序的控制器,是不是真的?

[window addSubview:rvcController.View];
[window makeKeyAndVisible];
Run Code Online (Sandbox Code Playgroud)

现在,UIWindow还有一个rootViewController属性.运行上一段代码时,是否使用rvcController填充了该属性,还是必须明确设置它?

然后,在UINavigationController中,可以设置与入口点的先前RVC集不同的RVC.

在这种情况下,我第一次将一个控制器添加到navigationController堆栈(在其上推一个新的控制器),框架是否将该控制器设置为navigationController的RVC,或者我是否必须通过initWithRootViewController方法显式设置它?

Jas*_*gun 20

呀..当我开始iPhone开发时.. rootViewController的事情也让我陷入了一个循环.但它真的很直接.

当应用程序启动时,我在我的app delegate类中创建了一个UIWindow对象.此外,在该类中,我有一个名为window的UIWindow类型的属性;

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

    UIWindow *w = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.window=w;
    [w release];
    // other code here...
}
Run Code Online (Sandbox Code Playgroud)

然后创建一个UIViewController,其view将在窗口层次结构中的第一个观点,这可以被称为"根视图控制器".

令人困惑的部分是...通常我们创建一个UINavigationController"根视图控制器",并且导航控制器有一个init方法,要求"RootViewController",这是它将放置在其堆栈上的第一个视图控制器.

因此,窗口有一个"根视图控制器",它UINavigationController也有一个RootViewController,它是你想要显示的第一个视图控制器.

一旦你解决了这一切,这一切都有道理......我想:-)

这里有一些代码可以完成所有工作..(取自我在我面前打开的项目)

//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;
}
Run Code Online (Sandbox Code Playgroud)


omz*_*omz 8

现在,UIWindow还有一个rootViewController属性.运行上一段代码时,是否使用rvcController填充了该属性,还是必须将其设置为明确?

您必须明确地设置它,如果这样做,您可以删除该addSubview行,因为在设置根视图控制器时会自动处理该行.

然后,在UINavigationController中,可以设置与入口点的先前RVC集不同的RVC.

当然,导航控制器的根视图控制器与窗口控制器无关.

在这种情况下,我第一次将一个控制器添加到navigationController堆栈(在其上推一个新的控制器),框架是否将该控制器设置为navigationController的RVC,还是必须通过initWithRootViewController方法设置它?

initWithRootViewController只是初始化空导航控制器并将第一个(根)视图控制器推入堆栈的快捷方式.请注意,这rootViewController不是属性UINavigationController,您可以通过它访问它[navController.viewControllers objectAtIndex:0].