将动画编程为在 Swift 中永远循环

Programming an animation to loop forever in Swift

我正在使用 Stack Overflow post 中的代码片段:How to make "shaking" animation

我将这段代码粘贴到我的项目中,它运行良好:

func shakeView(){
    var shake:CABasicAnimation = CABasicAnimation(keyPath: "position")
    shake.duration = 0.1
    shake.repeatCount = 2
    shake.autoreverses = true

    var from_point:CGPoint = CGPointMake(LoginField.center.x - 5, LoginField.center.y)
    var from_value:NSValue = NSValue(CGPoint: from_point)

    var to_point:CGPoint = CGPointMake(LoginField.center.x + 5, LoginField.center.y)
    var to_value:NSValue = NSValue(CGPoint: to_point)

    shake.fromValue = from_value
    shake.toValue = to_value
    LoginField.layer.addAnimation(shake, forKey: "position")
}

但是我希望这个动画循环播放直到调用另一个函数。如何让它无限循环以及如何让它在调用另一个函数时停止?

首先,设置 repeatCount to HUGE_VALF / greatestFiniteMagnitude:

Setting this property to HUGE_VALF will cause the animation to repeat forever.

其次,当你想停止动画时调用LoginField.layer.removeAllAnimations()LoginField.layer.removeAnimationForKey("position")

编辑:显然 Swift 不知道 HUGE_VALF,将 repeatCount 设置为 Float.infinity 应该有效。

使用shake.repeatCount = Float.infinity