使用 UIVIewPropertyAnimator 摇动视图

Shake view with UIVIewPropertyAnimator

我正在尝试使用完成处理程序编写抖动功能代码。当我调用 func 时,我可以看到摇晃本身,但它的幅度远小于期望值。请查看代码并帮助我修复错误。

func shake(_ completion: @escaping () -> Void) {
    let animator = UIViewPropertyAnimator(duration: 0.6, curve: .linear)
    let distances: [CGFloat] = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
    for (i, value) in distances.enumerated() {
        let delayFactor = Double(i) / Double(distances.count)
        animator.addAnimations({ [center, weak self] in
            self?.center = CGPoint(x: center.x + value, y: center.y)
        },
        delayFactor: CGFloat(delayFactor))
    }
    animator.addCompletion { _ in completion() }
    animator.startAnimation()
}

使用 addAnimations 方法添加的动画 运行 以及任何先前配置的动画 (source: Apple Documentation)。所以在你的情况下,你所有的动画都试图相互抵消。

如果您正在寻找类似 spring 的动画,请尝试使用 dampingRatio:

初始化动画师
myView.transform = CGAffineTransform(translationX: -20, y: 0)
let animator = UIViewPropertyAnimator(duration: 1.0, dampingRatio: 0.1) {
    self.myView.transform = .identity
}
animator.startAnimation()

如果这不是您想要的,您可能需要使用 keyframe animation