需要rootViewController澄清

时间:2011-10-12 03:10:21

标签: objective-c ios cocoa-touch uiviewcontroller uikit

将Controller定义为MainWindow.xib的一部分是应用程序的根控制器是否公平?

此外,假设RootController始终是负责向用户显示哪个视图的人?

1 个答案:

答案 0 :(得分:4)

一些标准的基于IB窗口的项目恰好是这种情况,但最终你需要一个窗口和一个视图来向用户展示一些东西。

只是视图:

考虑一下。我创建了一个空项目,添加一个视图(只是MyView.xib),为该代码添加一个按钮。没有根控制器 - 只是窗口和视图。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    UINib *nib = [UINib nibWithNibName:@"MyView" bundle:nil];
    UIView *myView = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];

    [[self window] addSubview:myView];
    [self.window makeKeyAndVisible];
    return YES;
}

对于典型的基于窗口:

-info.plist指向MainWindow.xib(主nib文件基本名称),文件所有者指向应用程序委托,app委托的viewController指向UIViewController。然后,通常将window rootviewController设置为上面设置的viewController。

- (BOOL)application:(UIApplication *)application didFinis hLaunchingWithOptions:    (NSDictionary *)launchOptions
{

    self.window.rootViewController = self.viewController;

但是,如果你看一下这个基于导航的应用程序(MasterDetail项目),就没有MainWindow.xib。

main.m指向appDelegate。

app delegate在navigationController中创建主控制器,以编程方式创建的navigationController成为rootViewContoller

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.

    MasterViewController *masterViewController = [[[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil] autorelease];
    self.navigationController = [[[UINavigationController alloc] initWithRootViewController:masterViewController] autorelease];
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    return YES;
}

最后,在这个程序化示例中,甚至没有设置windows rootViewController。
导航控制器的视图直接添加到窗口中。在一天结束时,窗口只是托管一个视图。您可以设置它或根控制器可以控制它。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // create window since nib is not.
    CGRect windowBounds = [[UIScreen mainScreen] applicationFrame];
    windowBounds.origin.y = 0.0;
    [self setWindow:[[UIWindow alloc] initWithFrame:windowBounds]];

    // create the rootViewController
    _mainViewController = [[MainViewController alloc] init];

    // create the navigationController by init with root view controller
    _navigationController = [[UINavigationController alloc] initWithRootViewController:_mainViewController];

    // in this case, the navigation controller is the main view in the window
    [[self window] addSubview:[_navigationController view]];

    [self.window makeKeyAndVisible];
    return YES;
}