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

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

    This seemed like the simplest solution for me.

    class SelfSizingCollectionView: UICollectionView {
        override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
            super.init(frame: frame, collectionViewLayout: layout)
            commonInit()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            commonInit()
        }
    
        private func commonInit() {
            isScrollEnabled = false
        }
    
        override var contentSize: CGSize {
            didSet {
                invalidateIntrinsicContentSize()
            }
        }
    
        override func reloadData() {
            super.reloadData()
            self.invalidateIntrinsicContentSize()
        }
    
        override var intrinsicContentSize: CGSize {
            return contentSize
        }
    }
    

    You may not need to override reloadData

提交回复
热议问题