0

I have to change the height of collection view with its dynamic cell height. cell height depends on its content and that cell height should update the height of collection view.

Nabin Rai
  • 1
  • 2

1 Answers1

0

If you're using UICollectionViewFlowLayout then you can use self sizing cells for UICollectionView and UITableView feature available from iOS 8 and above. This feature helps in dynamically setting the height of the cell based on the content and constraints set in the cell.

There are 2 step setup you need to do for self sizing cells to work.

1. Set estimatedItemSize on UICollectionViewFlowLayout:

//for storyboard:

if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
    flowLayout.estimatedItemSize = CGSize(width: UIScreen.main.bounds.width, height: 100)
}

//using code:

let flowLayout = UICollectionViewFlowLayout()
let collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: flowLayout)
flowLayout.estimatedItemSize = CGSize.init(width: UIScreen.main.bounds.width, height: 100)

2. Use Autolayout to configure custom UICollectionView cell or implement preferredLayoutAttributesFittingAttributes in your custom cell

var isHeightCalculated: Bool = false

override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    //Exhibit A - We need to cache our calculation to prevent a crash.
    if !isHeightCalculated {
        setNeedsLayout()
        layoutIfNeeded()
        let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
        var newFrame = layoutAttributes.frame
        newFrame.size.width = CGFloat(ceilf(Float(size.width)))
        layoutAttributes.frame = newFrame
        isHeightCalculated = true
    }
    return layoutAttributes
}

read stackoverflow and blog for more info on how to use autolayout for self sizing cells.

Suhit Patil
  • 10,286
  • 2
  • 42
  • 54