2

We have a horizontal animation like such:

UIView.animate(
    withDuration: 400.millisecond,
    delay: 600.milliseconds,
    options: [.autoreverse, .beginFromCurrentState, .allowUserInteraction],
    animations: {
        UIView.setAnimationRepeatCount(5)
        self.collectionView.transform = CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: -30, ty: 0)
}, completion: { _ in
    self.collectionView.transform = CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0)
})

We are doing so that the entire view content moved to the left a little bit (repeating twice) as an indication to the users that they can interact with our horizontal carousel (built with collection view).

However though, is there a way to cancel this animation if the user has interacted with the view?

There is a similar question asked: UIView animations canceling any touch input?. But it is not the same. What we are interested in is not only allowing user interaction but also cancel the animation immediately since we know that the user understands the UI already.

Yuchen
  • 30,852
  • 26
  • 164
  • 234
  • 1
    Use `UIViewPropertyAnimator`.. then you can set the value back to 0 to reverse the animation if you want.. Depends how you define cancel.. Does it just stop completely? Does it go back to how it was, etc.. In any case, `UIViewPropertyAnimator` should be the way to go imo.. – Brandon Nov 22 '18 at 18:33

1 Answers1

2

If just cancel animation, just terminate all animations like this:

     self.collectionView.layer.removeAllAnimations()

It's not pausing but to run completion block.

E.Coms
  • 11,065
  • 2
  • 23
  • 35