【问题标题】:Set orientation on UIViewController在 UIViewController 上设置方向
【发布时间】:2014-10-20 23:24:12
【问题描述】:

我正在尝试为UIViewController 设置方向,并禁止该UIViewController 上的所有方向更改。重要的是要注意该应用程序允许所有方向,但在这个视图控制器上,我只想允许纵向。

我正在使用 iOS 8,该应用适用于 iOS 6 及更高版本。所描述的行为发生在 iOS 7 和 8 中。我无法在 iOS 6 中对其进行测试,因此我不确定它是否发生在 iOS 6 中。

我实现了以下方法:

- (BOOL)shouldAutorotate
{
    return NO; // I've also tried returning YES - no success
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait; // I've also tried UIInterfaceOrientationPortrait - no success
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationMaskPortrait; // Never called
}

我已经能够为模态显示的视图控制器设置方向,但我没有为这个项目模态显示视图控制器。这也能做到吗?

如何为一个 UIViewController 指定方向,而不影响其他 UIViewController 的方向?这也能做到吗?

【问题讨论】:

  • 我也看到了这种行为(supportedInterfaceOrientations 未调用),但在我的情况下,目标是相反的(视图控制器应该支持旋转,而其他控制器不支持)。幸运的是,我可以切换 supportInterfaceOrientations 中返回的内容以在演示期间强制初始方向,但这对您没有帮助:(
  • iOS 6、7 和 8 中是否发生了错误行为?还是只有 8 个?
  • @Riley 我确定它发生在 iOS 7 和 8 中。我无法测试 iOS 6,所以我假设它也发生在 iOS 6 中。

标签: ios uiviewcontroller orientation


【解决方案1】:

假设您的视图控制器嵌入在导航控制器中,您需要使用UINavigationController 的自定义子类并添加:

- (BOOL)shouldAutorotate;
{
    BOOL shouldAutorotate;
    if ([self.topViewController respondsToSelector:@selector(shouldAutorotate)])
    {
        shouldAutorotate = [self.topViewController shouldAutorotate];
     }
     else {
        shouldAutorotate = [super shouldAutorotate];
      }
      return shouldAutorotate;
}

- (NSUInteger)supportedInterfaceOrientations
{
    NSUInteger supportedOrientations;
    if ([[self topViewController] respondsToSelector:@selector(supportedInterfaceOrientations)]) {
        supportedOrientations = [[self topViewController] supportedInterfaceOrientations];
    }
    else {
        supportedOrientations = [super supportedInterfaceOrientations];
    }
    return supportedOrientations;
}

在您的导航控制器中。视图控制器中的方法很好,所以保持原样。这适用于 iOS 7-8(尚未在 iOS6 中测试)

【讨论】:

  • 我使用了与此非常相似的解决方案。我刚刚创建了一个 UIForcedOrientationNavigationController 并用它包装了我的视图控制器。谢谢!
  • @eleven 很高兴它有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
相关资源
最近更新 更多