【问题标题】:Parent View Controller doesn't rotate while Child View Controller is presented呈现子视图控制器时父视图控制器不旋转
【发布时间】:2012-03-16 08:09:27
【问题描述】:

我有一个支持所有四个方向的父视图控制器。它呈现一个子视图控制器,如果在呈现子视图控制器时设备旋转,然后您关闭子视图,则父视图控制器不会正确旋转。这是我在父视图控制器中用于旋转的代码:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {

if (toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {

    newestIssueCoverImageButton.frame = CGRectMake(40, 20, 688, 865);
    shadow.frame = CGRectMake(40, 20, 688, 865);
    recordView.frame = CGRectMake(0, 44, 768, 916);
    classifiedsWebView.frame = CGRectMake(0, 44, 768, 916);

} else {

    newestIssueCoverImageButton.frame = CGRectMake(269, 20, 486, 613);
    shadow.frame = CGRectMake(269, 20, 486, 613);
    recordView.frame = CGRectMake(0, 44, 1024, 660);
    classifiedsWebView.frame = CGRectMake(0, 44, 1024, 660);

}

虽然没有使用此代码,但我只是旋转了设备。如何调用此代码并确保当用户当前正在查看子视图时父视图控制器正确旋转?感谢您的帮助。

【问题讨论】:

    标签: iphone objective-c ios ipad uiviewcontroller


    【解决方案1】:

    来自 Apple 的文档:

    如果发生方向变化时视图控制器不可见,则永远不会调用旋转方法。但是,viewWillLayoutSubviews 方法会在视图变得可见时调用。您对该方法的实现可以调用 statusBarOrientation 方法来确定设备方向。

    我添加了一个 BOOL 来跟踪当它不是顶部 viewController 时,然后:

    - (void)viewWillLayoutSubviews {
    
        if (notTopController) {
    
            [self willRotateToInterfaceOrientation:[[UIApplication sharedApplication] statusBarOrientation] duration:0];
            [self willAnimateRotationToInterfaceOrientation:[[UIApplication sharedApplication] statusBarOrientation] duration:0];
    
           notTopController = NO;
    
    }
    

    到目前为止对我来说效果很好。

    【讨论】:

    • 我必须根据我的情况调整它(我有一个容器视图控制器,它的大小不正确)但这里的基本逻辑是合理的。
    【解决方案2】:

    shouldAutorotateToInterfaceOrientation, willRotateToInterfaceOrientation, RotateToInterfaceOrientation 并且只在当前/可见视图控制器上调用,而不是在堆栈中“背后”的视图。在您的情况下,当孩子可见时,它会在孩子身上被调用,而不是在父母身上。

    如果发生了旋转事件,当您关闭子视图控制器时(假设您使用 NavigationController),将在父视图控制器上调用 shouldAutorotateToInterfaceOrientation(但 不是 will/didRotate) .如果您想亲自看看,请在所有这些方法中添加一些 NSLog() 语句。

    了解所有这些后,一个快速的解决方法是将调整大小的代码放入shouldAutorotateToInterfaceOrientation

    【讨论】:

    【解决方案3】:

    确保父视图控制器和子视图控制器都支持旋转。 shouldAutorotateToInterfaceOrientation:

    【讨论】: