为什么animateWithDuration淡出而不是?

时间:2015-06-30 02:58:50

标签: swift uiviewanimation swift2 animatewithduration xcode7-beta2

我在我的应用程序的一部分工作,我根据用户的时间进度动画消息。所以,基本上是时间消息。

我有一个柜台和两个标签:

var timer = NSTimer()
var timerCount = 0
@IBOutlet weak var bannerLabel: UILabel!
@IBOutlet weak var messageLabel: UILabel!

我有一个NSTimer调用count方法(countingUp),其中timerCount变量递增。当然,该方法会像人们期望的那样每秒触发。 countingUp方法调用名为updateLabels的方法(每秒)。

func countingUp() {
    // other irrelevant stuff
    updateLabels()
    timerCount++
}

func updateLabels() {           
   if timerCount == 1 {          
       animateMessage(messageLabel, delay: 7.0)
       animateBanner(bannerLabel, delay: 7.0)
       bannerLabel.text = "Message 1"
       messageLabel.text = "Blah Blah"
   }       
   // quite a few more of these conditions, though
   // I use a switch in my app.   
}

这是我的动画方法:

    func animateBanner(banner: UILabel, delay: Double){  
        UIView.animateWithDuration(1.2, animations: {
            banner.alpha = 1.0
        })

        if delay > 0.0 {
            UIView.animateWithDuration(3, delay: delay, options: [], animations: {
            banner.alpha = 0.1

            }, completion: nil)
         }
    }

    func animateMessage(label: UILabel, delay: Double){
        label.alpha = 0.0
        UIView.animateWithDuration(1.2, animations: {
            label.center.y -= 20
            label.alpha = 1.0
        })

        UIView.animateWithDuration(1.2, delay: delay, options: [], animations: {
            label.alpha = 0.1

            }, completion: nil)
    }

为了证明我的方法被调用并且我的标签确实处于0的alpha值,我拍摄了一个屏幕截图:

enter image description here

我的问题:

我的动画完美淡出,但它们永远不会消失,它们只会出现。这是什么原因?

1 个答案:

答案 0 :(得分:2)

动画发生在一个完成块中,所以基本上你同时运行两个动画,我在下面的代码中指出代码中发生了什么。

func animateMessage(label: UILabel, delay: Double){
        label.alpha = 0.0 
        //1 - Start animation 1
        UIView.animateWithDuration(1.2, animations: {
            //3 - Finish animation 1
            label.center.y -= 20
            label.alpha = 1.0
        })
        //2 - Start animation 2
        UIView.animateWithDuration(1.2, delay: delay, options: [], animations: {
             //4 - Finish animation 2
             label.alpha = 0.1
            }, completion: nil)
    }

你可以做的是在完成另一个动画时调用一个动画:

func animateMessage(label: UILabel, delay: Double){
        label.alpha = 0.0 
        UIView.animateWithDuration(1.2, delay: delay, options: [], animations: {
            label.center.y -= 20
            label.alpha = 1.0
        }, completion:{finished in
            if (finished) {
                UIView.animateWithDuration(1.2, delay: delay, options: [], animations: {
                     label.alpha = 0.1
                    }, completion: nil)
             }
    })
相关问题