NeoWang
NeoWang

Reputation: 18513

How to control the speed of UIView animation?

I am implementing a rotating digit view like this: https://github.com/jonathantribouharet/JTNumberScrollAnimatedView

But, instead of scrolling from say 1 to 9, I want the animation to continue scrolling (1 to 9 then back to 1 to 9), until I manually stop it.

I implement this by adding UILabel subviews 1-9, vertically stacked, and add an extra label for number 1 at the bottom. When rotating to the bottom (showing the bottom label 1), in the animation completion closure, I set the transform back to origin, showing top label 1, and restart rotating animation.

This works fine, but since each rotation (1-9-1) is separate, the animation from 1-9 accelerates and then stop at 1, and pick up speed at the next iteration. This is not what I want, I want the rotation to maintain a constant speed between the iterations.

How can I do this with UIView animation?

Here is the code:

 public func startAnimation(){
    UIView.setAnimationCurve(UIViewAnimationCurve.easeIn)
    UIView.animate(withDuration: TimeInterval(self.loopDuration), animations: { [unowned self] in
        self.container!.transform = CGAffineTransform(translationX: 0, y: CGFloat(-(self.endNumber-self.startNumber+1)*(self.size)))
    }) { [unowned self] (completed) in
        if self.isAnimationStopped {
            self.container!.transform = CGAffineTransform(translationX: 0, y: 0)
            UIView.setAnimationCurve(UIViewAnimationCurve.easeOut)
            UIView.animate(withDuration: TimeInterval(self.loopDuration), animations: {
                self.container!.transform = CGAffineTransform(translationX: 0, y: CGFloat(-self.targetY))
            })
        } else {
            self.container!.transform = CGAffineTransform(translationX: 0, y: 0)
            self.startAnimation()
        }
    }

}

Upvotes: 1

Views: 3628

Answers (1)

Duncan C
Duncan C

Reputation: 131398

By default UIView animation uses ease-in, ease-out animation timing, where the animation accelerates smoothly, runs, then decelerates to a stop.

You need to use a longer form of UIView.animate, animate(withDuration:delay:options:animations:completion:) that takes an options parameter, and specify a timing curve of .curveLinear.

Just specify 0.0 for the delay and options: .curveLinear

Edit:

Note that if you need to specify multiple options, like .curveLinear and .allowUserInteraction you would use OptionSet syntax, like options: [.curveLinear, .allowUserInteraction]

Upvotes: 6

Related Questions