UICollectionView wrong contentSize on first load, correct after that

klauslanza picture klauslanza · Aug 16, 2013 · Viewed 22.1k times · Source

I have a common UICollectionView with paging and all.

Still trying to figure out why on viewDidLoad:, viewWillAppear: and viewDidAppear: , only on first view call, I get the wrong size when calling myCollectionView.collectionView.contentSize.width. It always respond with 0 width (height is always correct). Successive reload of the view get me the correct one.

Resorted to using

self.collectionView.collectionViewLayout.collectionViewContentSize

which give me the correct width event on first load.

Still a mystery to me.

Answer

ucangetit picture ucangetit · Aug 4, 2015

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.