Search code examples
iosanimationuiviewanimationuiviewpropertyanimator

How to add animations to an already running animation based on the progress of the latter?


OBJECTIVE

Building a complex animation where some actions are triggered based on its progress.

QUESTION

Is it possible to check the progress of a UIViewPropertyAnimator and add animations when it reaches a given fraction complete that:

  • does not use UIView.animateKeyframes
  • does not require a user intervention

In other words, when the animator reaches a given fractionComplete, some animations are added to it.

ISSUES

The full animation comprises multiple animations of different objects (stored in an array). I need to both add animations at given times (based of % of completion) and add actions when some animations are completed.

Thanks for your kind help!


Solution

  • In some property, you can control delayFactor to add animation to replace previous target.

           let animView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 200))
        animView.backgroundColor = UIColor.green
    
     animator =    UIViewPropertyAnimator.init(duration: 5.0, curve: UIView.AnimationCurve.easeInOut)
    
        view.addSubview(animView)
        animator.addCompletion { (position : UIViewAnimatingPosition) in
            if position == UIViewAnimatingPosition.end{
                animView.center  = CGPoint.init(x: 100, y: 300)
            }
        }
        animator.addAnimations({
            animView.center  = CGPoint.init(x: 600, y: 300)
        })
        animator.addAnimations({
    
            animView.center = CGPoint.init(x: 200, y: 200)
        }, delayFactor: 0.1)
        animator.addAnimations({
    
            animView.center = CGPoint.init(x: 300, y: 600)
        }, delayFactor: 0.5)
        animator.addAnimations({
    
            animView.center = CGPoint.init(x: 400, y: 400)
        }, delayFactor: 0.9)
    
            animator.startAnimation()