我有一个非常基本的容器视图,其中包含一个侧边栏并交换内容区域中的视图控制器(想想UISplitView,但带有一个小图标侧边栏/垂直UITabBar)。
容器视图控制器使用autoLayout并在旋转时正确调整大小。 内容viewController 1使用autolayout并使用IB制作,因此它有一个xib文件。 内容viewController 2继承自UITableViewController,不使用xib。
如果我将viewController 1指定为根视图控制器并旋转,则调整大小会起作用,这里是我在viewController 1中得到的回调:
但是,如果我将容器视图控制器指定为根视图控制器,请加载viewController 1并旋转,则调整大小不起作用。我只在viewController 1中获得以下回调:
在我的视图控制器容器中,这是我交换视图控制器的方式:
[self addChildViewController:toViewController];
[toViewController didMoveToParentViewController:self];
// Remove the old view controller
[fromViewController willMoveToParentViewController:nil];
[fromViewController.view removeFromSuperview];
[fromViewController removeFromParentViewController];
// Add the new view
[self.contentContainerView addSubview:toViewController.view];
现在,我确实得到了一个旋转即将发生的回调,但似乎没有调用updateViewConstraints和viewWillLayoutSubviews。这解释了为什么调整大小没有发生,但是为什么在将视图控制器放在容器视图中时这些方法没有被调用?
我还尝试在两个
的容器中显式返回YESshouldAutomaticallyForwardAppearanceMethods
和
shouldAutomaticallyForwardAppearanceMethods
虽然这应该是默认值。
此外,在容器内旋转时,未使用IB(视图控制器2)制作的视图控制器可以正确调整大小。但是,我没有在这个上明确使用NSLayoutConstraints,所以我怀疑它是弹簧和Struts在旋转时调整大小的默认值。
我是否需要在视图控制器容器上转发其他一些事件以使自动布局视图控制器在旋转时正确调整大小?
答案 0 :(得分:3)
好的,我认为我在视图控制器容器中缺少此方法:
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
self.contentViewController.view.frame = self.contentContainerView.bounds;
}
虽然现在可以在旋转时正确调整大小,但仍然无法触发
updateViewConstraints
在我的子视图控制器中。有趣
答案 1 :(得分:0)
似乎iOS 8确实为您调用了updateViewConstraints。但iOS 7并没有。要在iOS 7中调用此方法,请调用setNeedsUpdateConstraints,如下所示:
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
{
[super willAnimateRotationToInterfaceOrientation:interfaceOrientation duration:duration];
BOOL isiOS7 = floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1;
if (isiOS7) {
// Trigger a call to updateViewConstraints
[self.view setNeedsUpdateConstraints];
}
}
在updateLayoutConstraints中,检查布局方向的一种好方法是检查状态栏的方向。这适用于7和8。
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
BOOL layoutAsLandscape = UIInterfaceOrientationIsLandscape(orientation);