2

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)]>
Community
  • 1
  • 1
Kevin
  • 16,696
  • 7
  • 51
  • 68

2 Answers2

0

Just try setup priority for each constraints

Bimawa
  • 3,535
  • 2
  • 25
  • 45
  • your answer should consist some links to help or the code or even some explanation . this can not be treated as answer – Nitin Jain Jan 30 '14 at 11:53
  • This simple conflict `CompressionResistance` with `height` of UILabel. This author need play with redundancy – Bimawa Jan 30 '14 at 13:31
  • I previously tried this, it stopped the crash but didn't solve the problem. – Kevin Jan 30 '14 at 15:51
0

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;
Kevin
  • 16,696
  • 7
  • 51
  • 68