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

问题描述:

我正在尝试显示基于混洗阵列的动画序列。Swift:For循环 - 在迭代之前等待动画完成

在我的ViewController我有4个UIButtons与标签(1,2,3,4)。

然后我有一个shuffledArray

shuffledArray = [3,2,4,1] 

我使用一个for循环并动态的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循环在点击按钮时激活。在for循环运行后,我生成一个1到4之间的随机数,然后将其附加到shuffledArray。因此,它开始的:

shuffledArray = [3] 

然后第二次是

shuffledArray = [3,2] 

而第三

shuffledArray = [3,2,4] 

等等....

这个问题似乎只有当数组包含多个项目时才会发生。

尝试这样? (未测试)

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() 
     } 
    } 
} 
+0

@JamesG你试过吗? – chengsam

+0

当shuffedArray获得两个项目时,它会将任何方块变成黑色。 – JamesG

+0

在调用'animateNext()之前将'currentIndex'重置为0' – chengsam

尝试使用延迟属性,像这样:

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) 
    } 

更新:

+0

该解决方案可能会更好,因为它更简单。 – chengsam

+0

这适用于第一个,然后它似乎一起跳其他3。 – JamesG

+0

@JamesG你确定每个按钮都有正确的标签吗? –