swiftuicollectionviewuicollectionviewflowlayoutios-animations

How can I implement this UICollectionView cell animation?


I've been wanting to implement this nice little UICollectionViewCell animation shown below that was on Dribble.

enter image description here

Do you think it's possible?

I looked around for any guides to get a head start on this but found nothing quite similar.

I have the idea that a custom flow layout is the way to go here. Would it be that I will have to make snapshots of each visible cell, add pan gestures to each cell and based on the movement detected through the gesture recogniser, capture visible cells and animate the snapshot images? Would appreciate any help to understand how I could implement this.

Thank you.


Solution

  • This is a pretty interesting challenge.

    Instead of doing a custom layout, I would override scrollViewDidScroll, store the offset every time it's called, compare it with the last stored offset in order to get the velocity, and based off of that, apply a transform to all visibleCells in your collection view.

    var lastOffsetX: CGFloat?
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
      defer { lastOffsetX = scrollView.contentOffset.x }
      guard let lastOffsetX = lastOffsetX else { return }
      // You'll have to evaluate how large velocity gets to avoid the cells
      // from stretching too much
      let maxVelocity: CGFloat = 60
      let maxStretch: CGFloat = 10
      let velocity = min(scrollView.contentOffset.x - lastOffsetX, maxVelocity)
      let stretch = velocity / maxVelocity * maxStretch
      var cumulativeStretch: CGFloat = 0
      collectionView.visibleCells.forEach { cell in 
        cumulativeStretch += stretch
        cell.transform = CGAffineTransform(translateX: cumulativeStretch, y: 0)
      }
    }
    

    I would start with something like this, and make lastOffsetX = nil when the scroll view stops scrolling (this exercise is left to the reader).

    It will probably require some tweaking.