Demo Code:
UIView *v = [[UIView alloc] initWithFrame:CGRectZero]; v.backgroundColor = [UIColor redColor]; v.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:self.v]; NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:v attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1 constant:0]; NSLayoutConstraint *heightConstraint= [NSLayoutConstraint constraintWithItem:v attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1 constant:0]; [v addConstraints:@[widthConstraint , heightConstraint]];以上代碼運行結果:
[LayoutConstraints] The view hierarchy is not PRepared for the constraint: <NSLayoutConstraint:0x6100000859b0 UIView:0x7f81c8d0ac50.width == UIView:0x7f81c8e08240.width (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. [LayoutConstraints] View hierarchy unprepared for constraint.Constraint: <NSLayoutConstraint:0x6100000859b0 UIView:0x7f81c8d0ac50.width == UIView:0x7f81c8e08240.width (active)>Container hierarchy: <UIView: 0x7f81c8d0ac50; frame = (0 0; 0 0); layer = <CALayer: 0x610000038b40>>View not found in container hierarchy: <UIView: 0x7f81c8e08240; frame = (0 0; 414 736); autoresize = W+H; layer = <CALayer: 0x600000037c80>>That view's superview: NO SUPERVIEW
解決方法是: NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:v attribute:NSLayoutAttributeWidth multiplier:1 constant:0]; NSLayoutConstraint *heightConstraint= [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:v attribute:NSLayoutAttributeHeight multiplier:1 constant:0]; [self.view addConstraints:@[widthConstraint , heightConstraint]];原理是:在viewDidLoad方法中,view的層級并沒有裝載完成,這個方法只是將所有UIView的實例加載到內存中,而沒有完成層級的組裝,這個時候,針對自定義的UIView子類的實例使用LayoutConstraint,參照對象是self.view, 就會產生Crash。但是,系統在self.view被顯示出來之前,會完成self.view的裝載,那么,self.view就是固定的,我們可以依據NSLayoutConstraint類提供的公式view1.attr1 <relation> multiplier × view2.attr2 + c進行反推。也就是解決辦法中的用法為什么可以解決問題的原因.關于公式,請參照:iOS 布局匯總
新聞熱點
疑難解答