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

后端 未结 14 1143
死守一世寂寞
死守一世寂寞 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:19

    I ended up, by subclassing the UICollectionView and overriding some methods as follows.

    • Returning self.collectionViewLayout.collectionViewContentSize for intrinsicContentSize makes sure, to always have the correct size
    • Then just call it whenever it might change (like on reloadData)

    Code:

    override func reloadData() {
        super.reloadData()
        self.invalidateIntrinsicContentSize()
    }
    
    override var intrinsicContentSize: CGSize {
        return self.collectionViewLayout.collectionViewContentSize
    }
    

    But be aware, that you lose "cell re-using", if you display large sets of data, eventhough they don't fit on the screen.

提交回复
热议问题