UIViewPropertyAnimator reverse animation

Viewed 7599

I have a simple pulse animation which runs perfectly

UIView.animate(withDuration: 1, animations: {
    myAnimatableView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}) { _ in
    UIView.animate(withDuration: 1, animations: {
        myAnimatableView.transform = .identity
    })
}

I want to make the same animation, but now with UIViewPropertyAnimator. Is it possible to replicate this pulse effect elegantly with the new API?

I'm doing it this way

let animator = UIViewPropertyAnimator(duration: 1, curve: .linear) {
    animatableView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}
animator.addCompletion { _ in
    animator.isReversed = true
    animator.startAnimation()
}
animator.startAnimation()

but my animatableView is just stuck scaled to 1.2.

2 Answers

I think your code is more appropiated translated like this

Try with this code

    let animator = UIViewPropertyAnimator(duration: 1, curve: .linear) {
        self.animatableView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
    }
    animator.addAnimations({
        self.animatableView.transform = CGAffineTransform.identity
    }, delayFactor: 0.5)
    animator.startAnimation()

Or you can try with UILayer animations

Try using UILayer animations

let layerAnimation = CABasicAnimation(keyPath: "transform.scale")
layerAnimation.fromValue = 1
layerAnimation.toValue = 1.2
layerAnimation.isAdditive = false
layerAnimation.duration = CFTimeInterval(1)
layerAnimation.fillMode = kCAFillModeForwards
layerAnimation.isRemovedOnCompletion = true
layerAnimation.repeatCount = .infinity
layerAnimation.autoreverses = true

self.animatableView.layer.add(layerAnimation, forKey: "growingAnimation")
Related