UICollectionViewCompositionalLayout incorrect item size

I'm currently facing an issue with compositional layout which can also be seen in Apple's example -> ConferenceNewsFeedViewController. The item height is set to .estimated(100) and the width is set to .fractionalWidth(1.0).

On the initial display the cell is not wrapping the label content. Only if you begin to scroll the layout of the cells are corrected. Does anybody know how to fix this issue?

I know that it can be "fixed" with the following, but this feels more like a dirty work around:

Code Block
DispatchQueue.main.async { self.collectionView.collectionViewLayout.invalidateLayout()
}

Any help to this is appreciated.


Best,
Carsten
I forgot to put the link to the example
I've got the same behavior. Only if you begin to scroll the layout of the cell is corrected.
Also if I update a multiline label's text within an already displayed self-sizing cell the layout is not updated automatically.

calling self.collectionView.collectionViewLayout.invalidateLayout() after changing the text is the only solution I found yet. But that feels like an overkill. I would have expected that AutoLayout takes care of it.

Implementing preferredLayoutAttributesFitting(_:) in my collection view cell fixed this problem:

override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    let targetSize = CGSize(width: layoutAttributes.frame.width, height: 0)
    let modifiedAttributes = super.preferredLayoutAttributesFitting(layoutAttributes)
    modifiedAttributes.frame.size = contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
    return modifiedAttributes
}

Having this issue on Xcode 12.5 & iOS 14.6 as well. Previously had no difficulty getting auto-height cells using NSCollectionLayoutSize.estimated() for heights, but now they only correct themselves after scroll begins.

Any resolution yet?

I have been experiencing the same issue with a compositional layout containing diverse layout sections with differing cell sizes. It seems to only occur with list cells when they are reloaded, so it occurred to me that the cell may not be updating its size on reuse. Overriding the prepare for reuse to invalidate the intrinsic content size seems to be working so far...

extension UICollectionViewListCell {   

    override open func prepareForReuse() {

        super.prepareForReuse()

        invalidateIntrinsicContentSize()

    }

}

Facing this issue for several days. The problem was simply that super.prepareForReuse() wasn't called in the Cell's prepareForReuse override...

Oh my God, you saved me. I have been banging my head against the wall for months on this one. THANK YOU!

UICollectionViewCompositionalLayout incorrect item size
 
 
Q