2017-08-30 108 views
1

我正在嘗試顯示基於混洗陣列的動畫序列。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] 

等等....

這個問題似乎只有當數組包含多個項目時纔會發生。

回答

0

嘗試這樣? (未測試)

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

0

嘗試使用延遲屬性,像這樣:

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你確定每個按鈕都有正確的標籤嗎? –

相關問題