如何按条件停止按钮动画

时间:2017-07-17 22:52:11

标签: swift animation uibutton removeall

我有一个功能可以将某个按钮设置为淡入和淡出。我在viewDidLoad中启动动画,因此一旦打开应用程序,动画就会正常工作。按钮将我带到输入窗口,当输入字段输入时,我希望动画停止。我试过用条件从文本中删除动画,但动画保持动画,即使条件满足。 我怎么能创建一个删除这个动画的功能?

继承我的代码:

func animateText(){

    UIView.animate(withDuration: 0.5, animations: {
        self.EnterDet.alpha = 1
    }, completion:  {
        (Comnpleted : Bool) -> Void in

        UIView.animate(withDuration: 0.5, delay: 1.5, options: UIViewAnimationOptions.allowUserInteraction, animations: {
        self.EnterDet.alpha = 0.1

        }, completion: {
            (Completed : Bool) -> Void in
            self.animateText()
        })
    })
}

1 个答案:

答案 0 :(得分:1)

更改完成块以检查completed参数。动画完成时(即未取消动画时)completedtrue。仅当completedtrue时,您才想调用动画的下一步。

UIView.animate(withDuration: 0.5, animations: {
    self.EnterDet.alpha = 1
}, completion:  {

(completed : Bool) -> Void in
    if completed {
        UIView.animate(withDuration: 0.5, delay: 1.5, options: UIViewAnimationOptions.allowUserInteraction, animations: {
            self.EnterDet.alpha = 0.1

        }, completion: {
            (completed : Bool) -> Void in
            if completed {
                self.animateText()
            } else {
                self.EnterDet.alpha = 1
            }
        })
    }
})

然后,当您想结束动画时,请致电:

self.EnterDet.layer.removeAllAnimations()