【问题标题】:Animate buttons by looping over an array通过在数组上循环来动画按钮
【发布时间】:2021-09-29 04:37:28
【问题描述】:

我正在用 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 种不同的颜色。第一种颜色将被忽略,只有第​​二种颜色有效果。你想让你的代码做什么?

标签: arrays swift for-loop animation


【解决方案1】:

您的代码的问题在于您在动画块中将按钮颜色设置为 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)
              }
            )
        }
}

【讨论】:

  • (上面的代码中几乎可以肯定至少有 1 个语法错误。它只是作为指导,你需要清理它。)
  • 非常感谢!这似乎现在可以正常工作了!
  • 你知道为什么一个按钮在数组中多次跳过两个实例的动画吗?
猜你喜欢
  • 2020-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-25
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
相关资源
最近更新 更多