Auto sizing UICollectionViewCell of UICollectionView fails in iOS 12

by

The content of my UICollectionView flows in horizontal direction. Height of items are fixed but width of each are dynamic based on the length of text. For this example I am using only UILabel in my UICollectionViewCell. My UICollectionViewCell is custom xib.

These are the constraints I have applied to UILabel:
  • Leading : 0
  • Trailing : 0
  • Top : 0
  • Height : 44

I have applied height constraint because I do not want height calculation processed for any intentional or non-intentional line breaks. I also make sure that number of lines in UILabel is 1 for my purpose because I do not want line breaks and ensures my layout lays out in horizontal list of one liners.

I have to set estimated size to automatic on layout:


((UICollectionViewFlowLayout *)collectionView.collectionViewLayout).estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize;

It works as long I am not building with iOS 12 base sdk. The output that I see looks like auto layout constraints are all ignored when building with iOS 12. Why? I have no detailed insight on this but I do have a workaround.

// The Workaround

I mentioned that I am using custom xib and subclass. Inside - (void)awakeFromNib I explicitly activate the constraints again.

- (void)awakeFromNib {
    [super awakeFromNib];
if (@available(iOS 12.0, *)) { self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
NSLayoutConstraint *leftConstraint = [self.contentView.leftAnchor constraintEqualToAnchor:self.leftAnchor constant:8]; NSLayoutConstraint *rightConstraint = [self.contentView.rightAnchor constraintEqualToAnchor:self.rightAnchor constant:8]; NSLayoutConstraint *topConstraint = [self.contentView.topAnchor constraintEqualToAnchor:self.topAnchor constant:0]; constraintEqualToAnchor:self.bottomAnchor constant:0]; NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:self.historyItemLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute: NSLayoutAttributeNotAnAttribute multiplier:1 constant:44]; [NSLayoutConstraint activateConstraints:@[leftConstraint, rightConstraint, topConstraint, heightConstraint]]; } }

You might also like: Sort an array of string containing numbers

You might also like: How to Fix Warning Attempt To Present UIAlertController

More Articles

Recommended posts