UICollectionView autosize height

前端 未结 9 1727
孤城傲影
孤城傲影 2020-12-04 07:02

How do I properly resize a UICollectionView so that it fully displays its contents? I have tried many things, including setting its frame, calling reloadData an

9条回答
  •  甜味超标
    2020-12-04 07:27

    You can try out my custom AGCollectionView class

    • Assign a height constraint of collectionView using a storyboard or programmatically.

    - Assign this class to your UICollectionView.

    class AGCollectionView: UICollectionView {
    
        fileprivate var heightConstraint: NSLayoutConstraint!
    
        override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
            super.init(frame: frame, collectionViewLayout: layout)
            self.associateConstraints()
        }
    
        required public init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            self.associateConstraints()
        }
    
        override open func layoutSubviews() {
            super.layoutSubviews()
    
            if self.heightConstraint != nil {
                self.heightConstraint.constant = floor(self.contentSize.height)
            }
            else{
                self.sizeToFit()
                print("Set a heightConstraint set size to fit content")
            }
        }
    
        func associateConstraints() {
            // iterate through height constraints and identify
    
            for constraint: NSLayoutConstraint in constraints {
                if constraint.firstAttribute == .height {
                    if constraint.relation == .equal {
                        heightConstraint = constraint
                    }
                }
            }
        }
    }
    

提交回复
热议问题