当视图从纵向更改为横向时,方向不会改变

Posted

技术标签:

【中文标题】当视图从纵向更改为横向时,方向不会改变【英文标题】:Orientation is not changed when view is changed from portrait to landscape 【发布时间】:2014-06-10 12:50:21 【问题描述】:

我有仅纵向的菜单和可以是纵向或横向的详细视图(带有UIWebView)。

当我进入详细视图并旋转设备横向并以这种方式从该屏幕返回到仅应为纵向的菜单时,菜单处于横向(以及状态栏和导航栏)。

有没有办法避免这种情况并强制屏幕旋转到所需(支持的)方向?

【问题讨论】:

【参考方案1】:

@kkumpavat 提出的解决方案对我不起作用,或者不够清楚,我无法理解。我做了更多搜索并找到了使用的解决方案:

    // http://***.com/questions/181780/is-there-a-documented-way-to-set-the-iphone-orientation
    // http://openradar.appspot.com/radar?id=697
    [[UIDevice currentDevice] performSelector:NSSelectorFromString(@"setOrientation:")
                                   withObject:UIInterfaceOrientationPortrait];

但这会产生烦人的警告,我已将其替换为:

//force update of screen orientation
if (self.interfaceOrientation != [self preferredInterfaceOrientationForPresentation]) 
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger: [self preferredInterfaceOrientationForPresentation]]
                                forKey:@"orientation"];

从 NavigationController 的 viewDidAppear 调用。

【讨论】:

setValue:forKey: 方法很漂亮。但它也是一个私有 API。这会导致我的申请被拒绝吗? (用于 ios 8) @Cutetare 我也很好奇。有人试过吗? 我最终为 iOS8 使用了另一种方法,请参阅***.com/questions/24907239/… 这绝对是错误的。如果你试图强制一个特定的界面方向,你想调用[UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationPortrait; Apple 提供了两个相似但非常不同的不同枚举:UIDeviceOrientation 和 UIInterfaceOrientation。设备属性是只读的,因为你不能强制物理设备改变方向! statusBarOrientation 可写的,并且会做你试图用 setValue:forKey: 做的事情【参考方案2】:

将菜单viewController的viewWillAppear改成如下

-(void)viewWillAppear:(BOOL)animated

    [super viewWillAppear:animated];
    UIViewController *controller = [[UIViewController alloc] init];
    [self presentViewController:controller animated:NO completion:nil];
    [self dismissViewControllerAnimated:NO completion:nil];

【讨论】:

我应该把它放在哪里?要离开详细视图,我在导航控制器栏中有后退按钮。 答案已更新。这样您就不必做太多事情了。 :) 你确定吗?这次更新后我只能看到黑屏了。 它会永远循环下去,哈哈

以上是关于当视图从纵向更改为横向时,方向不会改变的主要内容,如果未能解决你的问题,请参考以下文章

主视图控制器在点击项目并快速将方向从纵向更改为横向后消失

在Swift ios中方向更改为横向模式时隐藏底部表格视图

将 Cocos 2d 方向横向更改为纵向

UICollectionView 方向改变事故?

iOS CATiledLayer 崩溃

在自动布局中方向更改为横向时隐藏视图