How to adjust height of UICollectionView to be the height of the content size of the UICollectionView?

后端 未结 14 1117
死守一世寂寞
死守一世寂寞 2020-11-28 03:51

I would like the UICollectionView (The red one) to shrink to the height of the content size in this case UICollectionViewCells(the yellow ones) because there is a lot of emp

14条回答
  •  隐瞒了意图╮
    2020-11-28 04:11

    1. Subclass UICollectionView as follows
    2. Delete height constraint if any
    3. Turn on Intrinsic Size

    -

    class ContentSizedCollectionView: UICollectionView {
        override var contentSize:CGSize {
            didSet {
                invalidateIntrinsicContentSize()
            }
        }
    
        override var intrinsicContentSize: CGSize {
            layoutIfNeeded()            
            return CGSize(width: UIView.noIntrinsicMetric, height: collectionViewLayout.collectionViewContentSize.height)
        }
    }
    

提交回复
热议问题