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

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

    Took the solution by d4Rk which is great, except in my case it would keep cutting off the bottom of my collection view (too short). I figured out this was because intrinsic content size was sometimes 0 and this would throw off the calculations. IDK. All I know is this fixed it.

    import UIKit
    
    class SelfSizedCollectionView: UICollectionView {
        override func reloadData() {
            super.reloadData()
            self.invalidateIntrinsicContentSize()
        }
    
        override var intrinsicContentSize: CGSize {
            let s = self.collectionViewLayout.collectionViewContentSize
            return CGSize(width: max(s.width, 1), height: max(s.height,1))
        }
    
    }
    
    0 讨论(0)
  • 2020-11-28 04:32

    work for me

        let heightRes = resCollectionView.collectionViewLayout.collectionViewContentSize.height
        foodHeightConstrant.constant = height.advanced(by: 1 )
    
        foodCollectionView.setNeedsLayout()
        foodCollectionView.layoutIfNeeded()
    
    0 讨论(0)
提交回复
热议问题