自动旋转由视图的 UIViewController (shouldAutorotateToInterfaceOrientation:) 处理,因此一种方法是安排层次结构,使可旋转视图由一个视图控制器管理,不可旋转视图由另一个视图控制器管理。这两个 UIViewController 的根视图都需要添加到窗口/超级视图中。
这里的微妙之处在于,如果您在同一级别上有两个视图控制器的视图(即通过addSubview: 添加),则只有第一个视图控制器(通常是窗口的rootViewController)会收到shouldAutorotateToInterfaceOrientation: 消息。
我自己使用这种方法来实现一个可旋转的工具栏,而主视图则没有。
Apple's Technical Q&A QA1688 ("Why won't my UIViewController rotate with the device?") 稍微谈及这个问题。
iOS 6 更新:
自动旋转现在使用UIViewController 的shouldAutorotate 和supportedInterfaceOrientations 方法。 shouldAutorotate 默认返回 YES,但请记住,除了 rootViewController 之外的视图控制器,其视图是窗口的直接子视图,无论如何都不会收到旋转回调。
iOS 6 示例代码:
使用“单一视图应用程序”模板创建一个新项目,并确保选中“使用情节提要”。我们将使用提供的ViewController 类作为旋转视图控制器(如果愿意,可以重命名它!),并创建第二个UIViewController 子类NonRotatingViewController。虽然这个视图控制器永远不会收到旋转回调,但为了完整和清晰,在NonRotatingViewController.m 中添加以下代码:
- (BOOL)shouldAutorotate
{
return NO;
}
在MainStoryboard 文件中,拖出一个新的视图控制器对象并将其类设置为NonRotatingViewController,并将其Storyboard ID 设置为“NonRotatingVC”。当您在那里时,将旋转视图控制器视图的背景颜色更改为清除(非旋转视图将添加到此视图下方),并为每个视图添加一个标签。在AppDelegate.m中,添加如下代码:
#import "NonRotatingViewController.h"
// ...
// ...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
NonRotatingViewController *nonRotatingVC = [mainStoryboard instantiateViewControllerWithIdentifier:@"NonRotatingVC"];
[self.window addSubview:nonRotatingVC.view];
return YES;
}
这只是实例化一个非旋转视图控制器并将其视图直接添加到窗口(注意此时窗口的rootViewController 已经由情节提要设置)。
运行项目。旋转设备并惊叹于一个标签旋转而另一个保持静止的景象!
iOS 6 之前的示例代码:
我在一个新项目中这样做了——一个新的基于视图的应用程序就可以了。添加两个新的视图控制器:RotatingViewController 和 NonRotatingViewController。在他们的每个笔尖中,我只是添加了一个标签来描述视图是否应该旋转。添加以下代码:
'RotatingViewController.m'
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
'NonRotatingViewController.m'
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if (interfaceOrientation == UIInterfaceOrientationPortrait) { // Or whatever orientation it will be presented in.
return YES;
}
return NO;
}
'AppDelegate.m'
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
RotatingViewController *rotating = [[RotatingViewController alloc] initWithNibName:@"RotatingViewController" bundle:nil];
self.rotatingViewController = rotating;
[rotating release];
NonRotatingViewController *nonRotating = [[NonRotatingViewController alloc] initWithNibName:@"NonRotatingViewController" bundle:nil];
self.nonRotatingViewController = nonRotating;
[nonRotating release];
[self.window addSubview:self.rotatingViewController.view];
[self.window insertSubview:self.nonRotatingViewController.view belowSubview:self.rotatingViewController.view];
[self.window makeKeyAndVisible];
return YES;
}
我希望这会有所帮助。