Reputation: 1
LogoView is top_bg's subview. top_bg is window's subView. I try to add constraints with LogoView. Why I will get these wrong?
CGRect screenFrame = [[UIScreen mainScreen] bounds];
UIImageView *logoView = [[UIImageView alloc]init];//logo
UIImage *logoImage = [UIImage imageNamed:@"top_ico.png"];
[logoView setImage:logoImage];//below add constraint
// logoView.frame = CGRectMake(150.0f,0.0f, 304.74f, 60.0f);
[logoView setTranslatesAutoresizingMaskIntoConstraints:NO];
NSLayoutConstraint *logoConstraint_0 = [NSLayoutConstraint constraintWithItem:logoView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:top_bg attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f];
NSLayoutConstraint *logoConstraint_1 = [NSLayoutConstraint constraintWithItem:logoView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:top_bg attribute:NSLayoutAttributeLeft multiplier:1.0f constant:screenFrame.size.width/2.0f];
NSLayoutConstraint *logoConstraint_2 = [NSLayoutConstraint constraintWithItem:logoView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:304.74f];
NSLayoutConstraint *logoConstraint_3 = [NSLayoutConstraint constraintWithItem:logoView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:60.0f];
NSArray *LogoConstraints = [NSArray arrayWithObjects:logoConstraint_0,logoConstraint_1,logoConstraint_2,logoConstraint_3,nil];
[top_bg addConstraints:LogoConstraints];
[top_bg addSubview:logoView];
Below is the error when I run it.
2018-03-09 10:43:54.114041+0800 MainUI[1855:81910] [LayoutConstraints] The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x60000009b080 UIImageView:0x7f9196429a20.top == UIImageView:0x7f9196615d70.top (inactive)> 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.
Upvotes: 0
Views: 63
Reputation: 8904
You need to change the code sequence i.e. first add logoView as subview and then add its constraints.
First add Subview
[top_bg addSubview:logoView];
And the apply constraints
NSArray *LogoConstraints = [NSArray arrayWithObjects:logoConstraint_0,logoConstraint_1,logoConstraint_2,logoConstraint_3,nil];
[top_bg addConstraints:LogoConstraints];
Upvotes: 0
Reputation: 1
I got the answer !,like this code below
-(instancetype) initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if(self){
self.top_bg = [[UIImageView alloc]init];
self.logoView=[[UIImageView alloc]init];
[self.top_bg addSubview:self.logoView];
}
return self;
}
I must be confirm View's hierarchy before I add some constraints ! I can't add constrains then addSubViews.
Upvotes: 0