【发布时间】:2015-11-13 20:52:01
【问题描述】:
我正在阅读 iOS 教科书的第 16 章 Big Nerd Ranch,并尝试以编程方式添加约束(Xcode 7.1,iOS),但会导致以下错误:
The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x7f96f1e272a0 H:|-(0)-[UIImageView:0x7f96f1e3ba90]
(Names: '|':UIControl:0x7f96f1e33550 )>
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(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug.`
有BNRDetailViewController.xib 文件是BNRDetailViewController 的视图。这是我尝试在BNRDetailViewController 中使用的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
UIImageView *iv = [[UIImageView alloc] initWithImage:nil];
// The contentMode of the image view in the XIB was aspect fit
iv.contentMode = UIViewContentModeScaleAspectFit;
// Do not produce a translated constraint for this view
iv.translatesAutoresizingMaskIntoConstraints = NO;
// The image view was a subview of the view
[self.view addSubview:iv];
// The image view was pointed to by the imageView property
self.imageView = iv;
NSDictionary *nameMap = @{@"imageView": self.imageView,
@"dateLabel": self.dateLabel,
@"toolbar": self.toolbar};
// imageView is 0 pts from superview at left and right edges
NSArray *horizontalConstraints =
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[imageView]-0-|" options:0 metrics:nil views:nameMap];
// imageView is 8 pts from dateLabel at its top edge
// and 8 pts from toolbar at its bottom edge
NSArray *verticalConstraints =
[NSLayoutConstraint constraintsWithVisualFormat:@"V:[dateLabel]-[imageView]-[toolbar]" options:0 metrics:nil views:nameMap];
[self.view addConstraints:horizontalConstraints];
[self.view addConstraints:verticalConstraints];
}
【问题讨论】:
标签: ios objective-c constraints