2017-07-28 66 views
0

我想連續動畫多個按鈕,但是當需要動畫兩次或多次動畫時,代碼根本不起作用。如何在swift 3中延遲多次動畫對象?

//function that animates a button 
func buttonAnimationChain(buttonColor:UIButton, iDelayTime: Int){ 
    UIView.animate(withDuration: 0.5, delay: Double(iDelayTime), options: [], 
        animations: { 
        buttonColor.alpha = 0.0; 
    }, 
        completion: {finished in 
        buttonColor.alpha = 1.0; 
    }) 

} 
//function that displays the sequence 
func showSequence(iGeneratedArraySequence: [Int]){ 

    var iDelayTime:Int = 0; 

    for _ in 1 ... iGeneratedArraySequence.count{ 
     if(iGeneratedArraySequence[iDelayTime] == 1){ 
      buttonAnimationChain(buttonColor: buttonBlue, iDelayTime: iDelayTime); 
     } 
     if(iGeneratedArraySequence[iDelayTime] == 2){ 
      buttonAnimationChain(buttonColor: buttonYellow, iDelayTime: iDelayTime); 
     } 
     if (iGeneratedArraySequence[iDelayTime] == 3){ 
      buttonAnimationChain(buttonColor: buttonPurple, iDelayTime: iDelayTime); 
     } 
     if(iGeneratedArraySequence[iDelayTime] == 4){ 
      buttonAnimationChain(buttonColor: buttonGreen, iDelayTime: iDelayTime); 

     }//end of if statement 
      iDelayTime += 1; 
    }//end of for loop 
}//end of function 

當產生的數組只有那些不重複的數字,動畫作品完美,但一旦一個按鈕,需要進行兩次動畫,什麼也不顯示。我認爲這是因爲按鈕只是停留在非活動狀態,即使另一個函數變成活動狀態,我想不出一個解決方案來解決這個問題。我嘗試過使用sleep()函數,但這只是產生不可思議的結果。

回答

0
func buttonAnimationChain(buttonColor:UIButton, index : Int){ 
    UIView.animate(withDuration: 0.5, delay: 1.0, options: [], 
        animations: { 
        buttonColor.alpha = 0.0; 
     }, 
        completion: {finished in 
        buttonColor.alpha = 1.0; 
        if(index <= 4) 
        { 
         self.showSequence(index: index) 
        } 

    }) 

} 



func showSequence(index : Int){ 


    if(index == 1){ 
     buttonAnimationChain(buttonColor: buttonBlue, index: index + 1) 
    } 
    if(index == 2){ 
     buttonAnimationChain(buttonColor: buttonBlue, index: index + 1) 
    } 
    if (index == 3){ 
     buttonAnimationChain(buttonColor: buttonBlue, index: index + 1) 
    } 
    if(index == 4){ 
     buttonAnimationChain(buttonColor: buttonBlue, index: index + 1) 

    }//end of if statement 

} 

呼叫self.showSequence(索引:1)與索引1啓動動畫

+0

這個問題有點複雜。我需要按照一定的順序對盒子進行動畫處理,而不是使盒子來回閃爍。 –

+0

@RyanYang請檢查現在,請避免任何語法錯誤 –

0

的問題是,您所呼叫的動畫此起彼伏,而無需等待第一個結束和動畫的UIView是異步的。

也許你應該使用遞歸函數,用第一個按鈕調用它,當它結束時用第二個按鈕再次調用,等等。

+0

我也在想,但遞歸函數每次調用時都會創建一個新的作用域,所以如果它足夠長的動畫會導致內存泄漏,從而導致應用程序崩潰。 – ScottyBlades

+0

@ScottyBlades一定要添加一個終止條件,所以它不會永遠生成動畫,還要記住在每個動畫完成塊中添加'[weak self]',最後,不要忘記對所有動畫使用'weak'引用按鈕。有了這3個檢查,你應該沒有任何內存泄漏問題,保持循環或崩潰。 – zero