Swift:对于循环 - 等待动画在迭代之前完成



我正在尝试以洗牌数组的形式显示一系列动画。

在我的ViewController上,我有4个带有标签的Uibuttons(1,2,3,4)。

我有一个ShuffledArray

shuffledArray = [3,2,4,1]

我正在使用用于循环的循环循环循环,并为Uibutton的背景动画吗?

for square in shuffledArray {
        let btn = view.viewWithTag(square)
        
        UIView.animate(withDuration: 1, delay: 0.0, options:[], animations: {
            btn?.backgroundColor = .red
            btn?.backgroundColor = .black
            btn?.backgroundColor = .red
        }, completion: nil)
 }

但是,这只是使4个正方形同时闪烁黑色。

有没有办法运行此循环,但是要等每个动画先发射,然后再迭代到数组的下一个索引?

我尝试使用:

sleep(4)

和for循环的结尾,但这似乎冻结了我的应用程序,然后同时又改变了所有4个正方形。

侧注

在单击按钮上激活此循环。for循环运行后,我将在1到4之间产生一个随机数,然后将其附加到ShuffledArray。因此开始:

 shuffledArray = [3]

第二次是

 shuffledArray = [3,2]

和第三个

 shuffledArray = [3,2,4]

等等....

这个问题似乎只有在数组包含超过1个项目时发生。

尝试使用延迟属性,例如:

for (index, square) in shuffledArray.enumerated() {
        let btn = view.viewWithTag(square)
        UIView.animate(withDuration: 1, delay: index, options:[], animations: {
            btn?.backgroundColor = .red
            btn?.backgroundColor = .black
            btn?.backgroundColor = .red
        }, completion: nil)
    }

更新:

  • 尝试组合CAAnimationGroup的动画(https://developer.apple.com/documentation/quartzcore/caanimationgroup)。
  • 使用CAKeyframeAnimation-用于眨眼效果(https://developer.apple.com/documentation/quartzcore/cakeyframeanimation)

尝试这样的事情?(未测试)

var currentIndex = 0 
func animateNext() {
    if currentIndex < shuffledArray.count {  
        let btn = view.viewWithTag(shuffledArray[currentIndex])
        UIView.animate(withDuration: 1, delay: 0.0, options:[.autoreverse], animations: {
            btn?.backgroundColor = .red
            btn?.backgroundColor = .black
        }) { _ in
            self.currentIndex += 1
            self.animateNext()
        }
    }
}

最新更新