Equal height of UICollectionViewCell's and UICollectionView

Here is how I would do it. First add a global variable in the view controller which will be used to store the height of the collection view. In the viewDidLayoutSubviews method, set this variable to the height of the collectionView, and if it changed, call a method to invalidate the UICollectionView layout

collectionView.collectionViewLayout.invalidateLayout()

Which will call the method to set sizes of the collectionView cells, and in that method, set the height of the cell to the global variable holding the height of the collectionView.

Note: currently on my mobile and did not test this code. I might have missed something.


You try set this code to your viewDidLoad:

self.automaticallyAdjustsScrollViewInsets = false

Hope this help!


I had been struggling with this issue for over a week and finally found an answer that worked for my specific case. My issue was a result of 1) loading remote images in the UICollectionViewCell's image, and 2) having an estimated cell size that was larger than what I set manually on the sizeForItemAt of the collection view layout.

enter image description here

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height)
}

I was able to solve by reducing the cell size on the storyboard to an amount lower than my cell's size, and I also set "Estimate Size" to "None" (this last part is probably enough)