程序化界面方向更改不适用于iOS

所以,我有一个项目,当用户按下一个button时,我需要强制改变方向。 我已经在github上创build了一个示例应用程序来演示这个问题。

@interface DefaultViewController () { UIInterfaceOrientation _preferredOrientation; } 

一些旋转处理位

 - (BOOL)shouldAutorotate { return YES; } - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { return _preferredOrientation; } 

和一个切换

 - (IBAction)toggleButtonPressed:(id)sender { _preferredOrientation = UIInterfaceOrientationIsPortrait(_preferredOrientation) ? UIInterfaceOrientationLandscapeRight : UIInterfaceOrientationPortrait; [self forceOrientationChange]; } - (void)forceOrientationChange { UIViewController *vc = [[UIViewController alloc] init]; [self presentViewController:vc animated:NO completion:nil]; [UIView animateWithDuration:.3 animations:^{ [vc dismissViewControllerAnimated:NO completion:nil]; } completion:nil]; } 

所以,当你只是按下切换button,这似乎工作正常,它会改变方向如预期。 但是当我开始改变设备的实际方向时,存在一个问题。

重现问题的步骤:

  1. 以纵向打开应用程序
  2. 按下button强制方向改变为横向(保持实际设备为纵向)
  3. 再次按下button强制旋转回肖像(仍然保持设备的肖像)
  4. 无需按下button,将实际设备旋转到风景

结果是视图不会旋转到横向,而是状态栏。

强制方向更改问题

任何帮助将不胜感激!

我可以解决这个问题,通过添加下面的行之前呈现和解雇视图控制器:

 [UIViewController attemptRotationToDeviceOrientation]; 

这很难说,为什么这个工程。 这个调用要求尝试通过调用deviceOrientation来匹配interfaceOrientationdeviceOrientation shouldAutorotateToInterfaceOrientation:如果返回YES ,则后续的旋转方法。

看起来接口和设备的方向已经陷入了不同步的状态,因为尽pipe设备的方向,强制接口方向所需的解决方法。 尽pipe在我看来,仍然不应该发生,因为解决方法仍然是所提供方法的合法使用。 这可能是苹果的旋转/定向堆栈中的一个错误。

完整的方法:

 - (void)forceOrientationChange { UIViewController *vc = [[UIViewController alloc] init]; [UIViewController attemptRotationToDeviceOrientation]; /* Add this line */ [self presentViewController:vc animated:NO completion:nil]; [UIView animateWithDuration:.3 animations:^{ [vc dismissViewControllerAnimated:NO completion:nil]; } completion:nil]; } 

当我们谈论定位时,他们是两件事情,

设备方向界面方向仅以名称清楚,设备方向指示设备在哪个方向,而界面方向则表示应用呈现其界面的方向。

在这里,你正在做的是,你的应用程序支持所有的方向。 您必须在项目中勾选所有方向。

现在,当您将设备的方向从纵向更改为横向时,如果将interfaceOrientation设置为纵向模式,则会发生这种情况。 随着设备方向发生变化,状态栏的方向也会改变。 但是,由于您的应用程序界面被限制为纵向,所以不会改变其方向。

所以这是你可以做的:

  1. 取消选中您的应用的横向导向支持,并检查问题是否存在。
  2. 让我知道当你第一步时,发生了什么事情:)

使用此代码:

 UIApplication *application = [UIApplication sharedApplication]; [application setStatusBarOrientation:UIDeviceOrientationLandscapeLeft animated:YES]; [[UIDevice currentDevice] setOrientation:UIDeviceOrientationLandscapeLeft]; [super updateViewConstraints]; [self.view updateConstraints];