如何使iOS 6中的应用程序在自动旋转时完全正常工作?

17

iOS 6中,shouldAutorotateToInterfaceOrientation已被弃用。我尝试使用supportedInterfaceOrientationsshouldAutorotate来使应用程序在自动旋转时正常工作,但失败了。

我不希望这个视图控制器旋转,但它不起作用。

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(BOOL)shouldAutorotate
{
    return NO;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

有什么想法吗? 非常感谢您提前的帮助!


视图控制器是否嵌入导航控制器或选项卡控制器中? - Felix
嵌入导航控制器中。@phix23 - Carina
2个回答

38

我搞定了。

1) 继承 UINavigationController(层次结构的顶部视图控制器将控制方向)。

将其设置为 self.window.rootViewController。

- (BOOL)shouldAutorotate
{
    return self.topViewController.shouldAutorotate;
}
- (NSUInteger)supportedInterfaceOrientations
{
    return self.topViewController.supportedInterfaceOrientations;
}

2) 如果您不想让视图控制器旋转

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(BOOL)shouldAutorotate
{
    return NO;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

3) 如果你想要它可以旋转

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

-(BOOL)shouldAutorotate
{
    return YES;
}

顺便提一下,根据您的需求,另一种相关方法:

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
     return UIInterfaceOrientationMaskPortrait;
}

2
+1 是指在回答自己的问题时提供一些漂亮的代码示例。 - Robotic Cat
2
它适用于iOS 5.1或更高版本。除非您的应用程序部署目标是6.0。@voromax - Carina
不起作用。我的子类化UINavigationController从未调用-(BOOL)shouldAutorotate。 - Zigglzworth
你把它设置为self.window.rootViewController了吗?@Zigglzworth - Carina
当我们子类化UINavController时,我们究竟想要做什么?我有一个tab bar-> navbar -> uitablevc -> uivc的结构。我理解顶层层次结构会接管(在我的情况下是tabbarcontroller)。我需要强制我的tablevc为纵向显示,而uivc为左横向显示。 - marciokoko
显示剩余2条评论

3
如果你使用的是Tab Bar Controller而不是Navigation Controller作为根控制器,你需要同样地继承UITabBarController。另外,语法会有所不同。我成功地使用了以下代码,并在我想要重写的视图控制器上成功地使用了上述示例。在我的情况下,我希望主屏幕不旋转,但我有一个带有电影的FAQ屏幕,自然希望启用横向视图。完美解决!只需注意更改self.modalViewController的语法(如果你尝试使用导航控制器的语法,你会收到编译器警告)。希望这可以帮助你!
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)shouldAutorotate
{
    return self.modalViewController.shouldAutorotate;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return self.modalViewController.supportedInterfaceOrientations;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接