通过遍历数组来为按钮设置动画

Animate buttons by looping over an array

我正在 Swift 中制作一个简单的 'Simon Says' 风格的应用程序,我想闪烁按钮以显示用户必须遵循的顺序。

我制作了这个函数,它遍历按钮数组以暂时更改背景颜色。

func animateButtons() {
        for (index, button) in buttonSequence.enumerated() {
            UIButton.animate(withDuration: 1, delay: TimeInterval(index)) {
                button.backgroundColor = UIColor(red: 63/255, green: 255/255, blue: 0/255, alpha: 1.0)
                button.backgroundColor = UIColor(red: 168/255, green: 61/255, blue: 164/255, alpha: 0.85)
            }
        }
    }

现在虽然调用该函数时它会同时点亮所有按钮,但会动画化它们一个接一个地恢复到正常颜色。理想情况下,我希望它完全为一个按钮设置动画,然后是下一个按钮等。

我研究过为此使用计时器,但在搜索文档时找不到正确使用它的确切方法。

您的代码存在问题,您在动画块中将按钮颜色设置为 2 个不同的值。第一种颜色将被覆盖并且没有任何效果。

如果您希望每个按钮都变为动画块中的第一种颜色,按住 1 秒,然后恢复为第二种颜色,请像这样更改您的代码:

func animateButtons() {
        for (index, button) in buttonSequence.enumerated() {
            UIButton.animate(
              withDuration: 1, 
              delay: TimeInterval(index),
              animations: {
                button.backgroundColor = UIColor(red: 63/255, green: 255/255, blue: 0/255, alpha: 1.0)
               },
              completion: { finished in
                button.backgroundColor = UIColor(red: 168/255, green: 61/255, blue: 164/255, alpha: 0.85)
              }
            )
        }
}