如何检测View Controller的方向

时间:2016-04-12 11:40:05

标签: ios objective-c uiviewcontroller uiinterfaceorientation

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

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

  return NO;
}

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

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

您需要在导航期间使用attemptRotationToDeviceOrientation。您应该覆盖推/弹方法,以较小的UI延迟(attemptRotationToDeviceOrientation)来调用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

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

@implementation FirstViewController

.......

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{    
    return UIInterfaceOrientationMaskPortrait;
}

@end