Issue playing UIViewPropertyAnimator again

312 Views Asked by At

I am having an issue with UIViewPropertyAnimator, setup as follows:

let animator = UIViewPropertyAnimator(duration: 6.0, curve: .linear)

animator.addAnimations {
    UIView.animateKeyframes(withDuration: 6.0, delay: 0.0) {
        UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.1) {
            someView.alpha = 1.0
        }
        UIView.addKeyframe(withRelativeStartTime: 0.9, relativeDuration: 0.1) {
            someView.alpha = 0.0
        }
    }
}

@objc func didTapButton {
    if animator.isRunning {
        animator.isReversed = !animator.isReversed
    } else {
        print("start")
        animator.startAnimation()
    }
}

The first time I hit the button the animation plays fine. However the second time I hit it (after the animation completes) nothing happens. The animator has definitely stopped running (checked via the print statement) but it just doesn't respond.

What am I doing wrong here?

1

There are 1 best solutions below

2
Mikhail Vasilev On

According to UIViewPropertyAnimator documentation:

When the animator is stopped, either naturally completing or explicitly, any animation blocks and completion handlers are invalidated

In other words, when you call didTapButton second time, your animator has no animations.

To fix it, you should addAnimations every time user taps the button.

@objc func didTapButton {
    if animator.isRunning {
        animator.isReversed = !animator.isReversed
    } else {
        animator.addAnimations {... //insert you animations config ...}
        animator.startAnimation()
    }
}