1

I have a UICollectionView with expandable cells (just paste the following code into an empty project (xcode - new - uikit app with storyboard), it will work):

https://gist.github.com/smocer/e8c4bb3c5465c1a01bcf6aa33e0fd9dc

And I have a problem when cell expand and collectionview layout update animations are out of sync (the cell expands immediately, while other cells move smoothly):

Animation example

It's worth noting that collapse animation is actually in sync with UICollectionView animation for some reason.

The question is, how can I sync them without using hacks or workarounds? I mean, I can add some animations to the Cell's layer with Core Animation, but, I have to tune the duration value manually since I don't know what time it takes for UICollectionView to animate its items.

And if it's not possible, what is the best way to do it?

smocer
  • 119
  • 1
  • 10

2 Answers2

3

Try this out:

UIView.animate(withDuration: 0.3) {
    collectionView.performBatchUpdates({}) { _ in
        collectionView.layoutIfNeeded()
    }
}
Andrey Oshev
  • 846
  • 7
  • 17
  • Using collectionView.performBatchUpdates + collectionView.layoutIfNeeded is a life saver. Note, UIView.animate is not required as per my testing. – Cheok Yan Cheng Apr 16 '22 at 08:24
1

If you only change layout of the cell, there is no need to reload it and you could invalidate collectionViewLayout:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    isExpanded[indexPath.item].toggle()
    
    collectionView.collectionViewLayout.invalidateLayout()
    UIView.animate(withDuration: 0.25) {
        collectionView.layoutIfNeeded()
    }
}

Now items are expanding / collapsing with the same animation duration, which you could adjust too.

Viktor Gavrilov
  • 830
  • 1
  • 8
  • 13
  • Now it animates the closest cells correctly, but beginning from the cell #6 they just appear/disappear without any animation: https://i.imgur.com/78TOAL1.gif – smocer Aug 26 '21 at 13:22