我有一个 UIPageViewController,里面有一个简单的 UIViewController。
如果 UIViewController 没有 subview ,它的 View 在旋转时会正确调整大小。 (纯绿色背景)。
如果 UIViewController 有一个带有固定框架的 subview ,它的 View 在旋转时会正确调整大小。 (纯绿色背景,角落有黄色方 block )。
如果 UIViewController 有一个 subview ,其自动布局约束设置为填充其父 View ,则其 View 在旋转时不再正确调整大小。 (纯黄色背景,UIPageViewController 的红色背景可见)。我使用的自动布局代码是:
UIView *v = [[UIView alloc] init];
[v setTranslatesAutoresizingMaskIntoConstraints:NO];
[v setBackgroundColor:[UIColor yellowColor]];
[[self view] addSubview:v];
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(v);
NSArray *cs = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[v]|" options:0 metrics:nil views:viewsDictionary];
[[self view] addConstraints:cs];
cs = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[v]|" options:0 metrics:nil views:viewsDictionary];
[[self view] addConstraints:cs];
为什么 subview 的自动布局会影响它的父 View ?只有当它包含在 UIPageViewController 中时才会发生这种情况。
最佳答案
我也遇到了这个问题,之前的答案似乎没什么帮助。我需要为与 PageViewController 一起使用的 ScrollView 添加约束。
// Add Paging View Controller
self.addChildViewController(self.pageViewController)
self.pageViewController.didMoveToParentViewController(self)
self.containerView.addSubview(self.pageViewController.view)
// Add Constraints
var verticalConstraints:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:|[View]|", options: nil, metrics: nil, views: ["View":self.pageViewController.view])
var horizontalConstraints:Array = NSLayoutConstraint.constraintsWithVisualFormat("|[View]|", options: nil, metrics: nil, views: ["View":self.pageViewController.view])
self.pageViewController.view.setTranslatesAutoresizingMaskIntoConstraints(false)
self.containerView.addConstraints(verticalConstraints)
self.containerView.addConstraints(horizontalConstraints)
// Add Constraints for the Scrollview
//This line is a bit of a hack. If Apple ever changes the structure of the UIPageViewController, this could break.
let scrollView = self.pageViewController.view.subviews.first! as UIView
scrollView.setTranslatesAutoresizingMaskIntoConstraints(false)
verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[View]|", options: nil, metrics: nil, views: ["View":scrollView])
horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("|[View]|", options: nil, metrics: nil, views: ["View":scrollView])
self.pageViewController.view.addConstraints(verticalConstraints)
self.pageViewController.view.addConstraints(horizontalConstraints)
关于iphone - UIPageViewController + 自动布局旋转问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17729336/