Animate UICollectionView cell size change and reposition surrounding cells

11,339

Basically you need to do three steps

1.invalidate the collectionViewLayout

2.perform batch updates:

 ...
 //invalidate layout
[collectionView performBatchUpdates:^{
    // make your cell at indexPath return a new size
} completion:^(BOOL finished) {

}];

3.return the new size at sizeForItemAtIndexpath

Share:
11,339
Justin
Author by

Justin

Updated on June 27, 2022

Comments

  • Justin
    Justin almost 2 years

    enter image description here

    Goal:

    To animate the change of a cell's height and reposition surrounding cells.

    Scenario:

    Some cells in a collection view load remote images. Initially, those cells are sized statically and an activity indicator is shown. After an image is loaded, it is added to its cell and the cell's height is changed to fit the photo.

    Notes:

    I am animating the cell's frame change with animateWithDuration. This works fine, except an increased cell size has it overlapping the cells below. I've blindly tried calling collectionView.collectionViewLayout invalidateLayout after resizing the target cell and updating the size returned by sizeForItemAtIndexPath with no success.

    Any suggestions? Thank you!

    Sample Code:

    https://github.com/juzzin/ResizeUICollectionViewCell/blob/master/ResizeUICollectionViewCell/FLOViewController.m

    enter image description here

  • Justin
    Justin about 10 years
    Thank you Daniel. Appreciate your quick and succinct response. I posted some sample code and learned that performBatchUpdates calls invalidateLayout after animations complete. If explicitly called before performBatchUpdates, animations are skipped since the cell attributes are updated immediately. So, I believe you can skip the first step.
  • Skoua
    Skoua about 8 years
    I know I'm not supposed to say thank you but I've been struggling with this for DAYS and the solution is so simple! THANKS!! Thanks @Justin too for the Github link, very helpful.