在viewDidLoad中以编程方式添加布局约束

时间:2014-12-21 01:06:21

标签: ios objective-c uiviewcontroller autolayout nslayoutconstraint

在我的视图控制器[viewDidLoad]中,我正在以编程方式创建和添加子视图。

self.mainViewController = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
[self.view addSubview:self.mainViewController.view];
[self.view sendSubviewToBack:self.mainViewController.view];
[self addChildViewController:self.mainViewController];
[self.mainViewController didMoveToParentViewController:self];

这样可以正常工作,但由于打开了自动布局,因此效果不佳。我希望子视图填充它的父级的整个框架,所以我添加了一些约束。

NSDictionary *views = @{@"view" : self.mainViewController.view};
NSArray *vertical = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[view]-0-|" options:0 metrics:nil views:views];
NSArray *horizontal = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[view]-0-|" options:0 metrics:nil views:views];
[self.mainViewController.view addConstraints:vertical];
[self.mainViewController.view addConstraints:horizontal];

抛出

The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x7f9c9bd330b0 V:|-(0)-[UIView:0x7f9c9bc3bc30]   (Names: '|':UIView:0x7f9c9bf83fa0 )>
When added to a view, the constraint\'s items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView _viewHierarchyUnpreparedForConstraint:] to debug.

所以我的理解是父视图还没有完成构建,或者至少它与编程创建的子视图的关系。因此,无法在它们之间添加布局约束。那么问题是,如果我理解正确的话,我怎样才能创建这个子视图并在加载父vc后自动添加它?

0 个答案:

没有答案
相关问题