In my collection view I have an image with some text below. I have a height constraint for the image view so the image aspect ratio can be adjusted (cells are the width of the screen). I set the constraint constant in cellForItemAt. The cell heights only resize correctly after I scroll.
CollectionViewController
override func viewDidLoad(_ animated: Bool) {
super.viewDidLoad(animated)
let layout = collectionView.collectionViewLayout
if let flowLayout = layout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = CGSize(width: collectionView.widestCellWidth, height: 800)
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! selectCell
cell.setupView()
// Image resolution is already downloaded
let gsReference = storage.reference(forURL: thumbnail.storageLocation)
cell.imageView.sd_setImage(with: gsReference, placeholderImage: nil)
cell.layoutIfNeeded()
cell.layoutSubviews()
return cell
}
selectCell.swift
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
var targetSize = targetSize
targetSize.height = CGFloat.greatestFiniteMagnitude
let size = super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
return size
}
func setupView() {
// Changing the labels size the cell correctly when first loaded
titleLbl.text = ""
descriptionLbl.text = ""
let imageAspectRatio = CGFloat(metadata.thumbnail.width) / CGFloat(metadata.thumbnail.height)
let imageViewHeight = containerView.frame.width / imageAspectRatio
imageViewHeightConstraint.constant = imageViewHeight
self.contentView.setNeedsLayout()
self.contentView.layoutIfNeeded()
}