如何在swift 3中延迟多次动画一个对象?

时间:2017-07-28 06:09:08

标签: ios swift uiviewanimation

我想连续多次为多个按钮设置动画,但是当需要一个按钮来动画两次或更多时,代码根本不起作用。

//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()函数,但这只会产生不稳定的结果。

2 个答案:

答案 0 :(得分: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

}

使用索引1调用self.showSequence(index:1)以启动动画

答案 1 :(得分:0)

问题是你一个接一个地调用动画,而不是等待第一个结束,UIView动画是异步的。

也许你应该使用递归函数,用第一个按钮调用它,当它结束时再用第二个按钮调用它,依此类推。