某些基于标准 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 文件基名),File Owner 指向应用委托,应用委托的 viewController 指向 UIViewController。然后,通常将窗口 rootviewController 设置为上面设置的 viewController。
- (BOOL)application:(UIApplication *)application didFinis hLaunchingWithOptions: (NSDictionary *)launchOptions
{
self.window.rootViewController = self.viewController;
但是,如果您查看这个基于导航的应用程序(MasterDetail 项目),没有 MainWindow.xib。
main.m 指向 appDelegate。
应用程序委托在 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;
}