1

我试图让我的动画再次将屏幕从黑色变为白色,然后重复一定次数。目前使用代码,我的动画从黑色缓到白色,然后跳回黑色。无论如何要反向运行动画或添加在第一个动画完成后运行的动画?

override func viewDidAppear(_ animated: Bool) {
    let viewColorAnimator: UIViewPropertyAnimator = UIViewPropertyAnimator.runningPropertyAnimator(
        withDuration: 4.0,
        delay: 0.0,
        options: [.curveEaseInOut],
        animations: {
            UIView.setAnimationRepeatCount(3);
            self.lightView.backgroundColor = .white
        })

    viewColorAnimator.startAnimation()
}

我尝试将此代码块添加到项目中,但结果是相同的:

viewColorAnimator.addCompletion {_ in
    let secondAnimator = UIViewPropertyAnimator(duration: 4.0, curve: .linear) {
        self.lightView.backgroundColor = .black
    }
    secondAnimator.startAnimation()
}

编辑:我发现这是因为 setAnimationRepeatCount 因为最后一次迭代工作正常。如何在没有重复计数的情况下多次运行动画?

4

3 回答 3

2

文档说与方向相关的选项被忽略。你可以在这里查看附加的图片。

实现反向动画:

创建一个动画属性。

private var animator: UIViewPropertyAnimator = {

    let propertyAnimator = UIViewPropertyAnimator.runningPropertyAnimator(
    withDuration: 4.0,
    delay: 0.0,
    options: [.curveEaseInOut, .autoreverse],
    animations: {
        UIView.setAnimationRepeatCount(3)
        UIView.setAnimationRepeatAutoreverses(true)
        self.lightView.backgroundColor = .white
    })

    return propertyAnimator
}()

PS 我们需要在选项中提及 .autoreverse。否则 UIView.setAnimationRepeatAutoreverses(true) 将不起作用。

于 2018-09-07T09:24:46.250 回答
0

Xcode 9.4.1 (Swift 4.1.2)Xcode 10 beta 3 (Swift 4.2)

这是使用UIViewPropertyAnimator的方法——基本上,我们只需将.repeat.autoreverse添加到选项中。你已经完成了 99% 的工作:

override func viewDidAppear(_ animated: Bool) {
    let viewColorAnimator: UIViewPropertyAnimator = UIViewPropertyAnimator.runningPropertyAnimator(
        withDuration: 4.0,
        delay: 0.0,
        options: [.curveEaseInOut, .repeat, .autoreverse],
        animations: {
            UIView.setAnimationRepeatCount(3)
              self.lightView.backgroundColor = .white
        })

        viewColorAnimator.startAnimation()
    }
于 2018-07-11T17:24:41.423 回答
0

有一种运行动画的简单方法。对于这种方法:如果您希望动画在完成后重复,您可以添加 .autoreverse 和 .repeat 选项。像这样:

UIView.animate(withDuration: TimeInterval(randomTime), delay: 0, options: [.repeat,.autoreverse], animations: {
    //Animation code here
}, completion: {(bool)
   //Do something after completion
})

您可以将动画之后要执行的代码放在完成块中。

而且,您可以使用 Timer 作为在特定时间运行动画的一种方式。

于 2018-03-29T07:35:49.013 回答