Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView wrong contentSize on first load, correct after that

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.

like image 848
klauslanza Avatar asked Aug 16 '13 07:08

klauslanza


2 Answers

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.

like image 125
ucangetit Avatar answered Oct 18 '22 08:10

ucangetit


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) 
    }
like image 2
Muhammad Ali Avatar answered Oct 18 '22 08:10

Muhammad Ali