Ios – contentSize is not updated after reloadData is called on UICollectionView

iosuicollectionview

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 I've found is the following:

[_collectionView reloadData];

double delayInSeconds = 0.0001;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), ^(void)
    {
        // TODO: Whatever it is you want to do now that you know the contentSize.
    });

Obviously this is a fairly brittle hack that makes assumptions on Apple's implementation but so far it has proven to work quite reliably.

Does anyone have any other workarounds or knowledge on why this happens? I'm debating submitting a radar because this I can't understand why they cannot calculate the contentSize in the same run loop. That is how UITableView has worked for its entire implementation.

EDIT: This question use to reference the setContentOffset method inside the block because I want to scroll the collection view in my app. I've removed the method call because peoples' answers focused on why wasn't I using scrollToItemAtIndexPath inside of why contentSize is not being updated.

Best Answer

To get the content size after reload, try to call collectionViewContentSize of the layout object. It works for me.

Related Topic