Reloading a UICollectionView using reloadData method returns immediately before reloading data

Avner Barr picture Avner Barr · Aug 14, 2013 · Viewed 33.3k times · Source

I need to know when reloading a UICollectionView has completed in order to configure cells afterwards (because I am not the data source for the cells - other wise would have done it already...)

I've tried code such as

[self.collectionView reloadData];
[self configure cells]; // BOOM! cells are nil

I've also tried using

[self.collectionView performBatchUpdates:^{
  [self.collectionView reloadData];
    } completion:^(BOOL finished) {
        // notify that completed and do the configuration now
  }];

but when I reload the data I am getting crashes.

How can I reload the data into the collection, and only when it has finished reloading - do a particular completion handler

Answer

lukewar picture lukewar · Aug 21, 2013

This is caused by cells being added during layoutSubviews not at reloadData. Since layoutSubviews is performed during next run loop pass after reloadData your cells are empty. Try doing this:

[self.collectionView reloadData];
[self.collectionView layoutIfNeeded];
[self configure cells]; 

I had similar issue and resolved it this way.