How to make a UICollectionViewCell with dynamic height for iOS 14

198 views Asked by At

I have a problem resizing the cells of a collection view to fit their content. I have a method that works fine, but with iOS 14 this method fails and no longer works. The code I am using is:

In the layout (subclass of UICollectionViewFlowLayout:

- (CGRect)frameForItemAtIndexPath:(NSIndexPath *)indexPath
                      withYOffset:(CGFloat)yOffset {
  CGFloat x = 0.0;
  CGFloat y = yOffset;
  CGFloat width = self.collectionView.bounds.size.width - self.collectionView.contentInset.left - self.collectionView.contentInset.right;
  CGFloat height = [self.delegate heightForItemAtIndexPath:indexPath];
  
  return CGRectMake(x, y, width, height);
}

In the view controller:

- (CGFloat)heightForItemAtIndexPath:(NSIndexPath *)indexPath {
    MyCollectionViewCell *cell = [self.dataSource sizingCellAtIndexPath:indexPath];
    [cell setFrame:CGRectMake(cell.bounds.origin.x, cell.bounds.origin.y, UIScreen.mainScreen.bounds.size.width, cell.bounds.size.height)];
    CGSize size = [cell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize
                      withHorizontalFittingPriority:UILayoutPriorityRequired
                            verticalFittingPriority:UILayoutPriorityDefaultLow];
    return size.height;
}

As I said, this works fine until iOS 13.x but with iOS 14 fails and breaks the constraints. I have been searching a lot, and in stackoverflow there are a lot of answers but nothing seems to work for this.

Does someone know why this is not working on iOS 14 and how fix this?

Thanks in advance.

UPDATE

The method sizingCellAtIndexPath called in the first line of the method in the controller is:

- (MyCollectionViewCell *)sizingCellAtIndexPath:(NSIndexPath *)indexPath {
    Article *article = [self articleAtIndexPath:indexPath];
    NSString *cellIdentifier = [self cellIdentifierForCellAtIndexPath:indexPath];
    MyCollectionViewCell *sizingCell = [MyCollectionViewCell sizingCellWithNibName:cellIdentifier];
            
    [sizingCell configureWithArticle:article sizing:YES cellIdentifier:cellIdentifier indexPath:(NSIndexPath *)indexPath];
    [sizingCell setNeedsLayout];
    [sizingCell layoutIfNeeded];
            
    return sizingCell;
}
0

There are 0 answers