Question

I add a height layout constraint in code to my UICollectionViewCell subclass that sets the height based on the length of the text. See this question. I can post the code for the height calculations but I don't think that's the problem because it works perfectly for the first 4 cells, but then crashes on the 5th cell.

@property (weak, nonatomic) UILabel *name;

This is how I create the constraint.

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

And this is the error I get.

Unable to simultaneously satisfy constraints.

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

It seems I have 2 height constraints which makes no sense to me. In Interface Building I don't have height constraints (see screenshot). Label Screenshot

Printing out the constraints before the crash shows a height constraint.

<__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>
)

The constraint I calculate is

<NSLayoutConstraint:0x9ea9b50 V:[UILabel:0x9eb2e30(40.562)]>
Was it helpful?

Solution 2

UICollectionView reuses the all of it's UICollectionViewCell instances.. When one was taken offscreen, it was reused. Different cells required different heights, so the height constraints were different for each cell. The height constraints were not removed when the cell was reused, so that was the cause of multiple height constraints and the crash.

The solution was to not use auto layout and just modify the frame (Yes I tried removing the height constraint, didn't work).

CGRect labelFrame = self.name.frame;
labelFrame.size.height = labelSize.height;
self.name.frame = labelFrame;

OTHER TIPS

Just try setup priority for each constraints

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top