Does anyone know why contentSize is not updated immediately after reloadData is called on UICollectionView?
If you need to know the contentSize the best work around
Call prepareLayout first, and then you will get correct contentSize:
[self.collectionView.collectionViewLayout prepareLayout];
In my case, I had a custom layout class that inherits UICollectionViewFlowLayout
and set it only in the Interface Builder. I accidentally removed the class from the project but Xcode didn't give me any error, and the contentSize
of the collection view returned always zero.
I put back the class and it started working again.
Edit: I've just tested this and indeed, when the data changes, my original solution will crash with the following:
"Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (7) must be equal to the number of items contained in that section before the update (100), plus or minus the number of items inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out)."
The right way to handle this is to calculate the insertions, deletions, and moves whenever the data source changes and to use performBatchUpdates around them when it does. For example, if two items are added to the end of an array which is the data source, this would be the code:
NSArray *indexPaths = @[indexPath1, indexPath2];
[self.collectionView performBatchUpdates:^()
{
[self.collectionView insertItemsAtIndexPaths:indexPaths];
} completion:^(BOOL finished) {
// TODO: Whatever it is you want to do now that you know the contentSize.
}];
Below is the edited solution of my original answer provided by Kernix which I don't think is guaranteed to work.
Try performBatchUpdates:completion: on UICollectionView. You should have access to the updated properties in the completion block. It would look like this:
[self.collectionView reloadData];
[self.collectionView performBatchUpdates:^()
{
} completion:^(BOOL finished) {
// TODO: Whatever it is you want to do now that you know the contentSize.
}];
This worked for me:
[self.collectionView.collectionViewLayout invalidateLayout];
[self.collectionView.collectionViewLayout prepareLayout];
To get the content size after reload, try to call collectionViewContentSize
of the layout object. It works for me.