首页 文章

在关闭呈现的视图控制器时强制纵向模式

提问于
浏览
4

我有一个提供的视图控制器,支持所有的接口方向 . 但是,呈现视图控制器应仅支持纵向模式 .

到现在为止还挺好 .

但是,在iOS8中,当我在横向模式中关闭视图控制器WHILE时,横向模式保持不变 . 因为我将 shouldAutorotate 设置为 NO 它永远不会旋转回来 .

问题是,如何强制呈现VC返回肖像?

我目前已实施此解决方法:

- (BOOL)shouldAutorotate
{
  if ([self interfaceOrientation] != UIInterfaceOrientationPortrait)
  {
    return YES;
  }
  else
  {
    return NO;
  } 
}

它允许将设备移动到纵向,并且它将保留在此处,因为在它的肖像自动旋转被禁用之后 .

但在用户转动手机之前,它看起来很难看 .

怎么逼呢?

2 回答

  • 0

    我们遇到了完全相同的问题 . 您可以通过代码以编程方式旋转它 -

    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait) {
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    }
    

    有2种可能的选择 -

    1)在关闭呈现的viewController之前,如果需要,旋转到纵向

    2)解散后,在呈现viewController的“viewDidAppear”中旋转到肖像 .

    这个问题的一个问题是你无法传递完成块,但你可以在iOS8中使用下一个回调:

    -(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
    {
        if (self.needToDismissAfterRotatation)
            self.needToDismissAfterRotatation = NO;
            [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
            } completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
                // dismiss
            }];
        }
    }
    

    顺便说一句,在iOS8中苹果对屏幕旋转的方式做了很大的改变,当应用程序旋转,屏幕旋转,UIWindow中的所有元素也旋转,这就是为什么当呈现的viewController旋转到横向时,呈现viewController旋转,即使它只支持肖像...

    多年来我们一直在努力解决这个问题,最后我们提出了一个解决方案,将呈现的viewController放在一个新的UIWindow中,这样它就可以保持呈现viewController的纵向 all the time

    示例项目:"modalViewController" in UIWindow


  • 2

    假设您尝试强制纵向的视图控制器已经是根视图控制器(如果它不是根视图,此代码将恢复根视图控制器但不恢复任何其他操作,此代码将强制UI返回纵向查看已被推到它上面的控制器):

    UIInterfaceOrientation orientation = [[UIApplication 
        sharedApplication] statusBarOrientation];
    
    if (orientation != UIInterfaceOrientationPortrait) {
    
        // HACK: setting the root view controller to nil and back again "resets" 
        // the navigation bar to the correct orientation
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        UIViewController *vc = window.rootViewController;
        window.rootViewController = nil;
        window.rootViewController = vc;
    
    }
    

    它不是很漂亮,因为它在顶级视图控制器被解除后突然跳跃,但它比在横向上留下更好 .

相关问题