I am going through Big Nerd Ranch, iOS textbook's 16 chapter and trying to add constraints programmatically (Xcode 7.1, iOS) but it results in the following error:
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.`
There is BNRDetailViewController.xib
file that is the view of BNRDetailViewController
. Here is the code I am trying to use inside 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];
}