【问题标题】:Force portrait mode when dismissing a presented view controller关闭呈现的视图控制器时强制纵向模式
【发布时间】:2014-09-20 16:21:29
【问题描述】:

我有一个支持所有界面方向的视图控制器。但是,呈现视图控制器应该只支持纵向模式。

到目前为止一切顺利。

但是,在 iOS8 中,当我在横向模式下关闭视图控制器时,横向模式仍然存在。因为我将shouldAutorotate 设置为NO,所以它永远不会旋转回来。

问题是,如何强制呈现的 VC 恢复为纵向?

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

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

它允许将设备移动到纵向并且它会停留在这里,因为纵向自动旋转被禁用。

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

如何强制?

【问题讨论】:

    标签: uiviewcontroller ios8 device-orientation


    【解决方案1】:

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

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

    有 2 个可能的选项 -

    1) 在您关闭呈现的 viewController 之前,如果 需要

    2) 关闭后,在当前视图控制器的“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一直保持纵向

    示例项目: "modalViewController" in UIWindow


    【讨论】:

    • 先生,你救了我的命
    • @PaulBerg 耶!很高兴 2015 年我能帮上忙 :)
    【解决方案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;
    
    }
    

    它不是很漂亮,因为它会在顶级视图控制器被解除后突然跳转,但总比让它留在风景中要好。

    【讨论】:

      猜你喜欢
      • 2011-09-27
      • 1970-01-01
      • 2014-10-13
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      相关资源
      最近更新 更多