Self sizing UICollectionViewCell in iOS14
Asked Answered
S

2

5

enter image description here enter image description here Stack: Mac OS 10.15.6, Xcode Version 12.0 (12A7209)

I have a self sizing collection cell. I override preferredLayoutAttributesFitting to get the self sizing feature. Everything works great PRIOR to iOS 14 ("1"). However, in iOS 14 (when targeting the simulator or actual device), this cell seems to be "broken" that is, it's now shown ("2"). Furthermore, the layout engine complained about the layout constraints ("3").

Have you seen a similar issue?

Sneaky answered 21/9, 2020 at 16:24 Comment(0)
S
7

I had the same problem, the cell was looking good on iOS 11, 12, 13, but on iOS 14 simulator somehow the preferredLayoutAttributesFitting returned with the same height for every cell, ignoring that some cell needs more height.

The problematic code on iOS 14 (working on iOS 13 and below):

    override func preferredLayoutAttributesFitting(
        _ layoutAttributes: UICollectionViewLayoutAttributes
    ) -> UICollectionViewLayoutAttributes {
        layoutAttributes.bounds.size.height = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        return layoutAttributes
    }

However there is a contentView property that you can pass to this function (if your cell is subclass of UICollectionViewCell you already have that)

Solution (working on all iOS version I've tried):

    override func preferredLayoutAttributesFitting(
        _ layoutAttributes: UICollectionViewLayoutAttributes
    ) -> UICollectionViewLayoutAttributes {
        layoutAttributes.bounds.size.height = contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        return layoutAttributes
    }

and voila it works again.

I would appreciate if someone could explain what is happening here in the background, what has changed in iOS 14...

I'm not saying this is the solution for all iOS 14 self-sizing cell issue but it's worth a try! :)

Supinate answered 30/10, 2020 at 13:13 Comment(0)
C
2

Unfortunately the other answer didn't work for me, but I found another solution:

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

I got the solution from here

Contrarious answered 26/8, 2021 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.