ViewDidLoad中使用NSLayoutConstraint产生的问题解决


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 布局汇总



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值