0

I have a UICollectionView, which initial height is 50. I want to update it when I know the size of the cell. For what I do:

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    let categoriesCount = 16
    let numberOfItemsInRow = 3
    let numberOfRows = ceil(CGFloat(categoriesCount) / CGFloat(numberOfItemsInRow))

    let newHeight = (numberOfRows * cell.frame.size.height)

    collectionHeight.constant = newHeight
    collectionView.collectionViewLayout.invalidateLayout()
}

But despite of calling invalidateLayout - the height of the collectionView stays the same - 50.

But when I switch screens it shows the correct height when I open that screen with UICollectionView for the second time.

What I am doing wrong and how can I update the height of my UICollectionView?

I even tried collectionView.updateConstraints() after the collectionView.collectionViewLayout.invalidateLayout but still no luck

UPDATE

I've tried also

collectionView.layoutIfNeeded()
self.superview?.layoutIfNeeded()

but no result.

Apple John
  • 77
  • 7

3 Answers3

0

For this, you might have to call the self.view.layoutIfNeeded() method to force the view to update it's layout.

As per the documentation:

...this method lays out the view subtree starting at the root.

hence, updating your view

For more info, you can read this thread where you can pick bits and pieces to add to your solution.

Visal Rajapakse
  • 1,718
  • 1
  • 9
  • 15
0

Instead of trying to update the collectionView later based on the size of the cell, can we not use estimated height adjustment of the cell.

Maniac One
  • 589
  • 4
  • 23
0

Change the Estimated size option in size inspector of collection view to "None" from "Automatic". See the Image Below for reference.

enter image description here

I tried many answers given in different threads, none worked in my case but this one.

Check https://stackoverflow.com/a/59783595/11806784 this thread for reference.

Prank
  • 1
  • 1