如何处理子视图的方向更改

时间:2011-08-24 16:15:33

标签: iphone objective-c ios

我有两个UIViewControllers,UIViewControllerParent和UIViewControllerChild。在UIViewControllerParent内部我实例化一个子控制器并将其视图添加为子视图:

UIViewControllerChild *child = [[UIViewControllerChild alloc] init];
[self.view addSubView:child.view];

现在,当方向发生变化时,只有父视图控制器应调用AutorotateToInterfaceOrientation方法,并且只有父方向更改。孩子应该是否正确的行为是否应该调用ToTotInterfaceOrientation方法并且它的视图不会被旋转?

如果是这样,让子视图旋转的最佳实践方法是什么?应该有一种方法可以让子控制器自动布局,我只是不知道如何。

有什么建议吗?

3 个答案:

答案 0 :(得分:4)

  

只有父视图控制器应该调用AutorotateToInterfaceOrientation方法

这很正常。父视图的控制器负责确定支持的方向。来自Apple

  

注意:您可以将一个视图控制器的UIView属性添加为子视图   到另一个视图控制器。这样做,两个视图都会旋转但是   父视图控制器仍然负责确定   通过其shouldAutorotateToInterfaceOrientation支持的方向   方法

在该链接中还详细说明了您要检查的其他几项内容。

答案 1 :(得分:2)

这是Apple提供的一个项目,用于在方向发生变化时显示不同的XIB:https://developer.apple.com/library/ios/#samplecode/AlternateViews/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008755

否则,如果您想在方向更改时将子视图置于前面,请使用以下代码:

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

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

        [self.view bringSubviewToFront:portraitView];

    } else {

        [self.view bringSubviewToFront:landscapeView];

    }
}

请记住在头文件中定义一个新的UIView并将其链接到XIB文件中。

答案 2 :(得分:0)

最好不要在ViewController中创建ViewControllers。

在您的情况下,您可以将子ViewController视图的引用添加到根ViewController。并保留由根ViewController管理的所有内容。