2017-07-28 36 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