在iOS 6中,模态视图控制器如何强制横向方向?

8

我有一个在竖屏模式下显示的UITabBarController。在其中一个选项卡上,我有一个按钮,可以以模态形式显示一个UIViewController(使用简单的故事板segue执行操作)。

我希望此模态视图在横向模式下显示,但我无法使其自动旋转。

在模态视图控制器中,我有以下内容:

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

我已经在 .plist 支持的方向中添加了 landscapeLeft(尽管这也允许 TabBar 旋转,但我不希望)

我还将此添加到模态视图的 ViewDidLoad 中

[UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationLandscapeLeft;

但是我无法让它自己旋转。

谢谢

编辑 ----

似乎 shouldAutoRotate 没有被调用!

另外,我正在尝试检测方向,但以下代码始终显示2,无论方向如何!

if ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortrait) {
        NSLog(@"1");
        self.hostView.frame = CGRectMake(0, 60, 200, 255);
    } else {
        NSLog(@"2");
        self.hostView.frame = CGRectMake(0, 45, 480, 255);
    }

编辑2 ---

抱歉,我应该提到我正在使用iOS 6。在iOS 5上,显示屏会自动旋转。 shouldAutorotateToInterfaceOrientation已经被弃用,因此我需要研究新的方法。


根据我以前的经验来看,没有办法强制一个视图控制器以特定的方向出现。你可以选择是否允许方向发生变化,但不能强制改变它。对我来说,这真是个令人沮丧的事情... - KDaker
这有点愚蠢!我有一个只适合横向显示的图表。所以你的意思是苹果希望我在用户旋转设备之前就把它弄糟了吗?这听起来不太对,尽管我还没有找到解决方案,所以你可能是对的。 - Darren
4个回答

7
iOS 6.0发布说明:“越来越多的职责转移到了应用程序和应用程序委托上。现在,iOS容器(如UINavigationController)不会向它们的子视图查询以确定是否应自动旋转。”
在IOS6中,无论是在任何容器下(如UINavigationController),UIViewController的-(BOOL)shouldAutorotate方法都不会被调用。
可以尝试使用类别(Category)的解决方案将方法添加到现有的UINavigationController类中。
shouldAutorotate方法内部,您可以调用每个self.viewControllers视图控制器中的shouldAutorotate方法。事实上,您可以将其传递给您的子视图控制器。

6

如果您想在iOS6中强制旋转,请确保您的rootViewController实现以下方法:

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

- (BOOL)shouldAutorotate {
    return YES;
}

1

在 iOS 6 中,似乎使用这个方法可以强制指定方向。

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

我仍在尝试使其工作,并将随时更新任何发现。


谢谢,这在我的情况下与方法-(BOOL)shouldAutorotate{ return NO;}一起工作。 - Alexey

0

我在我的应用程序中确切地这样做,并通过shouldAutoRotateToInterfaceOrientation实现,与您略有不同:

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
 if (UIInterfaceOrientationIsLandscape(interfaceOrientation))
  return (YES);
 return (NO);
}

对于 iOS 6,您还必须在应用程序委托中设置 window.rootViewController = {您的根视图控制器}。我希望这是您的问题。


这仍然不能强制更改方向。我已将此添加到我的AppDelegate中: self.window.rootViewController = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"mainTab"]; - Darren
好吧,有点遗憾,我的应用程序中没有使用故事板,但我不认为这会引起问题。我怀疑rootViewController属性是否已经自动设置给你了。记录shouldAutorotate的调用可能会很有趣,看看它是否被调用了。 - CSmith
不,shouldAutorotate根本没有被调用! - Darren
1
糟糕。shouldAutorotateToInterfaceOrientation在iOS 6中已经被弃用了。我想我应该提到我正在使用它。 - Darren

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