【问题标题】:How to detect orientation of View Controller如何检测视图控制器的方向
【发布时间】:2016-04-12 11:40:04
【问题描述】:

我有三个视图控制器,它们都被推送到我已经子类化的导航控制器上,以便只允许在第二个视图控制器中旋转,我这样做,

- (BOOL)shouldAutorotate
{    
  if ([self.topViewController isKindOfClass:[SecondViewController class]])
      return YES;

  return NO;
}

我在自定义导航控制器中编写了这段代码,问题是如果我以纵向模式打开我的应用程序,然后将方向更改为横向模式,我的视图控制器不会旋转,但即使我的第二个视图控制器打开它以纵向模式打开,但我希望它以横向模式打开,因为它支持旋转。

我怎样才能做到这一点?

【问题讨论】:

  • 当您将设备前后移动时,它会旋转吗?
  • 你实现func supportedInterfaceOrientations() -> UIInterfaceOrientationMask了吗?
  • 是的,在打开第二个视图控制器并且我旋转设备后它可以正常旋转
  • 一定要推吗?或者展示视图可以吗?
  • 我正在推送视图

标签: ios objective-c uiviewcontroller uiinterfaceorientation


【解决方案1】:

导航时需要使用attemptRotationToDeviceOrientation。你应该重写 push/pop 方法来调用 attemptRotationToDeviceOrientation 有一个小的 UI 延迟 (dispatch_async)

@implementation CustomNavigationController

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [super pushViewController:viewController animated:animated];

    [self updateOrientaion];
}

- (nullable UIViewController *)popViewControllerAnimated:(BOOL)animated
{
    [self updateOrientaion];

    return [super popViewControllerAnimated:animated];
}


- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    if ([self.topViewController isKindOfClass:[SecondViewController class]])
        return UIInterfaceOrientationMaskAll;

    return UIInterfaceOrientationMaskPortrait;
}


- (void)updateOrientaion
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIViewController attemptRotationToDeviceOrientation];
    });
}

@end

但是当你弹出到UINavigationController 的rootViewController 时,supportedInterfaceOrientations 会为rootViewController 调用。所以你还需要为FirstViewController实现supportedInterfaceOrientations

@implementation FirstViewController

.......

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{    
    return UIInterfaceOrientationMaskPortrait;
}

@end

【讨论】:

  • 非常感谢这个工作!虽然当我的第二个视图控制器加载时有一个轻微的动画我怎么能停止动画,因为它给用户一种旋转的感觉。
  • 一直在寻找这个解决方案。谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-25
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
相关资源
最近更新 更多