具有交错开始时间的 CAKeyframeAnimation

CAKeyframeAnimation with staggered begin time

我正在尝试创建一个动画,其中项目会及时交错显示。为此,我使用了 CAKeyframeAnimation,但为了实现惊人效果,我需要指定 beginTime

问题是我还希望动画在完成时不要快速回到原来的位置,所以我在模型上指定值如下:view.layer.transform = CATransform3DIdentity before 动画添加到图层中。

但是,动画确实会快速回到初始位置,因为我已经指定了 beginTime。有解决办法吗?

func addAnimation(view: UIView, index: Int) {
    let values = RK4SpringAnimation(tension: 600, friction: 60, initialVelocity: 0) // just provides an array of values between 0.0 and 1.0.
    let positions = values.map { Float(view.layer.frame.width) - (Float([=10=]) * Float(view.layer.frame.width)) }
    let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
    animation.values = positions
    animation.duration = 0.716
    animation.beginTime = CACurrentMediaTime() + Double(index) * 0.015
    view.layer.transform = CATransform3DIdentity // set the final value on the model.
    view.layer.add(animation, forKey: "transform2")
}

我用来解决这个问题的一种方法是为您的动画设置 CAAnimationDelegate 并实现 animationDidStop(CAAnimation, finished: Bool)。创建对视图图层的引用,并在动画结束时设置所需的变换。

添加动画后,应将 属性 值设置为动画的最终值。最后的值是CATransform3DIdentity?

如果动画的beginTime在未来,并且动画的开始值不等于它的结束值,那么你可以设置animation.fillMode = .backwards告诉Core Animation应用动画的开始值到层,直到达到 beginTime

func addAnimation(view: UIView, index: Int, show: Bool) {
    let values = RK4SpringAnimation(tension: 600, friction: 60, initialVelocity: 0) // just provides an array of values between 0.0 and 1.0.
    let positions = values.map { Float(view.layer.frame.width) - (Float([=10=]) * Float(view.layer.frame.width)) }
    let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
    animation.values = positions
    animation.duration = 0.716
    animation.beginTime = CACurrentMediaTime() + Double(index) * 0.015
    animation.fillMode = .backwards
    view.layer.add(animation, forKey: animation.keyPath)
    view.layer.setValue(positions.last!, forKey: animation.keyPath!)
}