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.