由于额外的高度限制,Autolayout崩溃

时间:2014-01-25 17:54:03

标签: ios autolayout nslayoutconstraint

我在代码中将高度布局约束添加到我的UICollectionViewCell子类中,该子类根据文本的长度设置高度。 See this question.我可以发布高度计算的代码,但我不认为这是问题,因为它适用于前4个单元格,但随后在第5个单元格上崩溃。

@property (weak, nonatomic) UILabel *name;

这是我创建约束的方式。

NSLayoutConstraint *labelHeightContraint = [NSLayoutConstraint constraintWithItem:self.name attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:labelSize.height];
[self.name addConstraint:labelHeightContraint];

这就是我得到的错误。

Unable to simultaneously satisfy constraints.

(
    "<NSLayoutConstraint:0x9ff8770 V:[UILabel:0x9ff72d0(60.843)]>",
    "<NSLayoutConstraint:0x9feb590 V:[UILabel:0x9ff72d0(40.562)]>"
)

我似乎有2个身高限制,对我来说没有任何意义。在Interface Building中我没有高度限制(见截图)。 Label Screenshot

在崩溃显示高度限制之前打印出约束。

<__NSArrayM 0x9eb0a00>(
<NSLayoutConstraint:0x9ea1670 V:[UILabel:0x9eb2e30(60.843)]>,
<NSContentSizeLayoutConstraint:0x9fa0580 H:[UILabel:0x9eb2e30(72)] Hug:251 CompressionResistance:750>,
<NSContentSizeLayoutConstraint:0x9fa7bf0 V:[UILabel:0x9eb2e30(61)] Hug:251 CompressionResistance:750>
)

我计算的约束是

<NSLayoutConstraint:0x9ea9b50 V:[UILabel:0x9eb2e30(40.562)]>

2 个答案:

答案 0 :(得分:0)

只需尝试每个约束的设置优先级

答案 1 :(得分:0)

UICollectionView重复使用所有UICollectionViewCell个实例。当一个屏幕被取消时,它会被重复使用。不同的细胞需要不同的高度,因此每个细胞的高度限制是不同的。重复使用单元格时不会删除高度限制,因此导致多个高度限制和崩溃。

解决方案是不使用自动布局,只修改框架(是的,我尝试删除高度约束,不起作用)。

CGRect labelFrame = self.name.frame;
labelFrame.size.height = labelSize.height;
self.name.frame = labelFrame;
相关问题