ios - 编程界面方向更改不适用于 iOS

标签 ios objective-c rotation orientation

所以,我有一个项目,我需要在用户按下按钮时强制改变方向。我创建了一个 sample app on github来证明这个问题。

@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];
}

所以,当您按下切换按钮时,这似乎工作正常,它会按预期更改方向。但是当我开始改变设备的实际方向时,出现了问题。

重现问题的步骤:

  1. 纵向打开应用
  2. 按下按钮强制将方向更改为横向(保持实际设备为纵向)
  3. 再次按下按钮强制旋转回纵向(仍保持设备纵向)
  4. 在不按下按钮的情况下将实际设备旋转为横向

结果是 View 不会旋转到横向,但状态栏会旋转。

Forced orientation change issue

如有任何帮助,我们将不胜感激!

最佳答案

我能够通过在呈现和关闭 View Controller 之前添加以下行来解决此问题:

[UIViewController attemptRotationToDeviceOrientation]; 

很难说清楚为什么会这样。此调用要求尝试通过调用 shouldAutorotateToInterfaceOrientation:interfaceOrientationdeviceOrientation 匹配,如果 YES 为回来。

由于强制界面方向所需的解决方法,尽管设备方向,界面和设备方向似乎变得不同步。尽管在我看来仍然不应该发生,因为解决方法仍然是对所提供方法的合法使用。这可能是 Apple 的旋转/方向堆栈中的错误。

完整方法:

- (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];
}

关于ios - 编程界面方向更改不适用于 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21101003/

相关文章:

android - 使用应用程序而不是浏览器打开 Twitter URL

ios - 迁移到 Swift 4 后 RxSwift 'Extra argument ' onError'

ios - StoreKit 更改商店通知?

jquery - UI 选项卡旋转窃取焦点

java - LWJGL 旋转物体

iphone - 从未调用过 shouldStartLoadWithRequest 委托(delegate)方法

iOS 更改 Chartboost 委托(delegate)

ios - iOS-从文本字段获取参数时,修剪前是否应检查null?

objective-c - 使用 CFWriteStream 将文件传输到套接字

c++ - directx 11 基于旋转移动对象