UICollectionView wrong contentSize on first load, correct after that

In my case, I was always getting content size zero. layoutIfNeeded() was not enough for me I have to get content size inside DispatchQueue.main.async ie

    self.collectionView.layoutIfNeeded()
    DispatchQueue.main.async {
        print(self.collectionView.contentSize) 
    }

So I was seeing a similar issue where contentSize width was always zero. The simple answer is...there is probably no content in the collectionView yet. That was why it's content size is zero.

I was also noticing that sometimes after calling invalidateLayout on my UICollectionView, I was seeing that self.collectionView.collectionViewLayout.collectionViewContentSize was not the same as self.collectionView.contentSize.

After much searching I found a great hint here in this SO post

What I needed to do to get both contentSize calculations to be the same was to call [self.collectionView layoutIfNeeded] immediately after calling [self.collectionView reloadData] or [self.collectionView.collectionViewLayout invalidateLayout].

This essentially forces the reload to happen immediately instead of on the next runloop cycle.

I really hope this solves your issue.