Search code examples
swiftuiviewpropertyanimator

How can I increment a value while UIViewPropertyAnimator is going through the animation process?


How can I increment a value while UIViewPropertyAnimator is going through the animation process? As I have set my object in motion I would like to increment its value as it drops on my screen but I am not sure how to link that with my Animator. Any suggestions? Here is how I have initiated the

let toTravel = CGFloat(blockSize * newInstance.distanceToTravel()) //checks how far it needs to go.
let frame = CGRect(x: x, y: startY, width: width, height: height)
super.init(frame: frame)
backgroundColor = UIColor.clear
addSubBlocksToView(grid: grid, blockSize: blockSize)
animator = UIViewPropertyAnimator(duration: 10.0, curve: .linear) { [unowned self] in
    self.center.y += toTravel // need to calculate CODE this it is a static right now
}

As you can see it takes 10 seconds to travel the distance I have calculated. I would like to keep track of each few pixels (30) it has traveled with a counter.


Solution

  • Set up a CADisplayLink when you start the animation. During the animation, you can check the current position (given that it is a linear animation, you could do this easily by initialPosition + time/10 * distance). Once the animation has completed, you can invalidate the display link. The display link provides you with a callback for every frame, which you can use to update your onscreen counter.

    Alternatively you could consider using a CADisplayLink to drive the entire animation (and use a custom animation curve driven by your own code.)