强制设备旋转时+ attemptRotationToDeviceOrientation失败

根据这里的UIViewController文档,

https://developer.apple.com/library/ios/documentation/uikit/reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/clm/UIViewController/attemptRotationToDeviceOrientation

使用[UIViewController attemptRotationToDeviceOrientation]强制系统尝试将界面旋转到新的方向。 我试图强制从纵向到横向的界面旋转:

  • 在尝试旋转之前设置forceLandscape标志
  • 调用[UIViewController attemptRotationToDeviceOrientation]
  • 在我的视图控制器中实现-supportedInterfaceOrientations并检查标志以更改支持的方向,例如

这迫使-supportedInterfaceOrientations再次被调用,看起来像

 - (NSUInteger)supportedInterfaceOrientations { return self.forceLandscape ? UIInterfaceOrientationMaskLandscapeLeft : UIInterfaceOrientationMaskPortrait; } 

即使正在调用-supportedInterfaceOrientations并返回新的方向,接口也不会旋转。 我已经确认该项目允许所有的方向,并且这个视图控制器是窗口的根视图控制器。 有没有其他人遇到这个问题,并find一个解决scheme? 我知道所有的窍门,以解决这个问题(提交和解雇模态等),但我希望有一个干净的解决scheme,如果可能的话。 我已经在iOS 6和7上validation了这个问题。

以下是完整的代码重现:

 @interface ALTViewController () @property (nonatomic, assign) BOOL forceLandscape; @end @implementation ALTViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { self.forceLandscape = NO; } return self; } - (void)viewDidLoad { [super viewDidLoad]; UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; [button setTitle:@"button" forState:UIControlStateNormal]; [button sizeToFit]; [self.view addSubview:button]; button.center = self.view.center; [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside]; } - (void)buttonPressed:(id)sender { self.forceLandscape = YES; [UIViewController attemptRotationToDeviceOrientation]; } - (NSUInteger)supportedInterfaceOrientations { return self.forceLandscape ? UIInterfaceOrientationMaskLandscapeLeft : UIInterfaceOrientationMaskPortrait; } 

调用attemptRotationToDeviceOrientation只旋转接口的方向,当且仅当设备本身已被旋转。

例如,如果您的视图控制器仅支持纵向,并且用户将设备旋转到横向,则不会发生界面旋转。 当设备处于横向方向时,让我们说你的代码切换一个标志,允许横向方向。 界面方向会发生什么? 没有,因为设备方向已经发生。 要使界面方向与设备方向匹配,您需要调用attemptRotationToDeviceOrientation。

在我自己的代码中,我最近创build了一个自定义的多部分视图animation,如果在它的中间发生了界面旋转,看起来不正确。 所以我在简短的animation中closures了界面旋转。 如果用户在animation期间旋转了设备,则不会发生界面定向。 但是,当接口方向被打开时,接口将不会旋转以匹配设备方向,直到我调用了attemptRotationToDeviceOrientation。

您可以尝试使用以下方法实现:setStatusBarOrientation:animated: https : //developer.apple.com/library/ios/documentation/uikit/reference/UIApplication_Class/Reference/Reference.html#//apple_ref/occ/instm/UIApplication/ setStatusBarOrientation:animation :

这为我解决了类似的问题。