很多人可能都遇到过这种问题:把一个TabBarController压栈到一个NavigationController中后,对TabBarController的视图控制器里的视图使用自动布局,当添加一个view.top = self.topLayoutGuide.bottom后,发现view一部分被NavigationBar挡住了。这是因为在is中,TabBarViewController里面的视图控制的的topLayoutGuide的length只有20个像素,处理方法是重载viewWillLayoutSubiews方法,改变约束的constant值,如下:
为了方便,我们不再添加view.top = self.topLayoutGuide.bottom的约束,而是添加view.top = self.topLayoutGuide.top的约束:
self.topLayoutGuideConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.topLayoutGuide attribute:NSLayoutAttributeTop multiplier:1 constant:0];
[self.view addConstraint:self.topLayoutGuideConstraint];
- (void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
self.topLayoutGuideConstraint.constant = [self.tabBarController.topLayoutGuide length];
}
在viewWillLayoutSubviews调用以后,tabBarController.topLayoutGuide的lenth是状态栏的高度和导航栏的高度之和
实际上不只是tabBarController存在这种问题,child viewController和 parent viewController之间也存在这种问题