是的,将它添加到 UIWindow 会非常麻烦和挑剔。
故事板
如果您使用 Storyboards 和 iOS 5.0 及更高版本,您应该能够使用容器视图并执行以下操作:
这是另一张图,展示了第一个 View Controller 的结构,相当简单:
左侧的视图控制器有一个容器,然后是一个将按钮放在其顶部的视图。该容器指示导航控制器(直接在右侧)应该出现在其自身中,这种关系由=([])=> 箭头(正式称为embed segue)表示。最后,导航控制器将其根视图控制器定义到右侧。
总而言之,第一个视图控制器在容器视图中煎饼,按钮在顶部,所以里面发生的一切都必须让按钮在顶部。
使用 childViewControllers
又名。 “我讨厌故事板和小狗”模式
使用与 Storyboard 版本类似的结构,您可以创建带有按钮的基本视图控制器,然后在下面添加将成为应用程序新“根”的视图。
为了清楚起见,我们将持有按钮的视图控制器称为FakeRootViewController,而实际上,该视图控制器将成为应用程序的根:RootViewController。所有后续的视图控制器甚至都不知道FakeRootViewController 在其他所有人之上。
FakeRootViewController.m
// The "real" root
#import "RootViewController.h"
// Call once after the view has been set up (either through nib or coded).
- (void)setupRootViewController
{
// Instantiate what will become the new root
RootViewController *root = [[RootViewController alloc] <#initWith...#>];
// Create the Navigation Controller
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:root];
// Add its view beneath all ours (including the button we made)
[self addChildViewController:nav];
[self.view insertSubview:nav.view atIndex:0];
[nav didMoveToParentViewController:self];
}
AppDelegate.m
#import "FakeRootViewController.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
FakeRootViewController *fakeRoot = [[FakeRootViewController alloc] <#initWith...#>];
self.window.rootViewController = fakeRoot;
[self.window makeKeyAndVisible];
return YES;
}
这样,您可以享受在窗口上插入按钮的所有好处,而不会感到内疚和“我真的应该成为一名程序员吗?”它引起的。