当视图帧为零时,无法同时满足约束

时间:2017-10-19 03:03:53

标签: swift nslayoutconstraint

我创建了视图

init(){
   super.init(frame: .zero)
}

创建视图后,我想设置我的子视图

func setViews(){
    self.addSubview(labelView)
    self.addConstraintsWithFormat("V:|-10-[v0]-10-|", views: labelView)
    self.addConstraintsWithFormat("H:|-10-[v0]-10-|", views: labelView)
}

一切正常,但我警告

Probably at least one of the constraints in the following list is one you
don't want. Try this: (1) look at each constraint and try to figure out
which you don't expect; (2) find the code that added the unwanted
constraint or constraints and fix it. (Note: If you're seeing
NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the 
documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 


 (
        "<NSLayoutConstraint:0x7f87ea8e6520 V:|-(10)-[BIPartners.labelView:0x7f87eb56be20]   (Names: '|':BIPartners.labelView:0x7f87eb56a320 )>",
        "<NSLayoutConstraint:0x7f87ea8e6af0 V:[BIPartners.labelView:0x7f87eb56be20]-(10)-|   (Names: '|':BIPartners.labelView:0x7f87eb56a320 )>",
        "<NSLayoutConstraint:0x7f87e868bdc0 '_UITemporaryLayoutHeight' V:[BIPartners.labelView:0x7f87eb56a320(0)]>"
    )

我知道问题是当我将帧设置为零时。我将帧设置为零,并将垂直边距设置为10.我应该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

使用WTF Auto Layout了解您的错误。

在设置约束之前检查视图的bounds。如果它等于CGRect.zero,请不要应用约束。

答案 1 :(得分:0)

您应该通过将标签的底部钉扎约束的优先级降低到小于1000的值来解决此问题:

self.addConstraintsWithFormat("V:|-10-[v0]-10(@750)-|", views: labelView)

这将消除您的约束,消除底部填充和标签的内在高度。

基本上,当您想要使用内在内容大小并且标签固定在两侧时,会出现这种歧义。

当然,还有其他方法可以获得所需的间距(边距),但这个答案最接近你想要做的。