Delay after each animation iteration in Swift

2019-07-20 18:03发布

问题:

I have a Core Animation whose .repeatCount is set to Float.infinity. After each iteration of the Animation, ie. after each repetition, I want to have a delay of 3 seconds. How can I achieve this? Thanks!

回答1:

You can use a function like the following to do what you need.

func animateInfinitelyWithDelay(delay : NSTimeInterval,duration : NSTimeInterval) {

    UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.CurveEaseIn,
        animations: { () -> Void in

        // Your animation Code

    }) { (finished) -> Void in
        if finished {
            self.animateInfinitelyWithDelay(delay, duration: duration)
        }
    }

}


回答2:

You could also use a UIView keyframe animation (animateKeyframesWithDuration) where there is "dead time" built into the animation at the end, and then repeat that animation.



回答3:

One way to accomplish this effect using Core Animation is to configure everything except the repeat count on the original animation object and then wrap it in an animation group with a longer duration and repeat that animation group instead.

let originalAnimation = /* create and configure original animation ... */
originalAnimation.duration = shortDuration

let group = CAAnimationGroup()
group.animations = [originalAnimation]
group.duration = shortDuration + delayAtTheEnd
group.repeatCount = .infinity

theLayer.add(group, forKey: "repeating animation with delay between iterations")

Note that depending on what the original animation is doing, you may need to configure a fill mode to achieve the right look.