1

I have an override function for my collection view:

    // Sets a the width as the screen width and has a dynamic height that changes depending on how much is inside the cell.
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    let targetSize = CGSize(width: layoutAttributes.frame.width, height: 40)
    layoutAttributes.frame.size = contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
    print("Layout has been changed.")
    return layoutAttributes
}

This function makes the cell heights dynamic depending on the height of the contents inside the cell while keeping the width a static width of the phone screen. This function works exactly how I want it to work.

The problem that I am having is this function is only called when the view loads, and I want it to also run when I call collectionView.reloadData(). So when I call reloadData() the cell goes off of its estimatedItemSize instead of its size from the function above preferredLayoutAttributes.

Does anyone know how I can allow this function to run when I call collectionView.reloadData()?

1 Answers1

-1

This works for me:

extension UICollectionView{
func reloadData2(_ completion: @escaping () -> Void) {
        UIView.animate(withDuration: 0, animations: {
            self.reloadData()
        }, completion: { _ in
            completion()
        })
    }

}

  • Unfortunately that didn't work for me :(. Function is still not being called. Am I calling it correctly? `self.collectionView.reloadData2 {}` – CoderDude123 Dec 22 '21 at 22:47
  • Call your function inside the curly braces …reloadData2 {Yourfunction()} – Akos Farkas Dec 24 '21 at 08:43
  • In addition, if you can change the collectionview to a uitableview, you can use the autodimension. https://stackoverflow.com/questions/30494702/dynamic-height-issue-for-uitableview-cells-swift – Akos Farkas Dec 24 '21 at 12:06