UIViewanimation跳过第一个animation

对这个抱歉很新!

一旦我运行按button“按”UIView“背景”的背景颜色立即改变为蓝色,然后animation到紫色,完全跳过animation黄色,然后到蓝色。

我做错了什么?

@IBAction func Press(sender: AnyObject) { UIView.animateWithDuration(5, animations: { self.Background.backgroundColor = UIColor.yellowColor() self.Background.backgroundColor = UIColor.blueColor() self.Background.backgroundColor = UIColor.purpleColor() }, completion:{(Bool) in println("COLOR CHANGED") }) } 

在单个UIView.animateWithDuration调用中,您不能将多个状态更改设为同一个属性。 它只是animation到最后一个状态的变化(就像你的情况)。 相反,您可以使用completionBlock它们链接在一起。

 UIView.animateWithDuration(5/3.0, animations: { self.view.backgroundColor = UIColor.yellowColor() }, completion:{ finished1 in UIView.animateWithDuration(5/3.0, animations: { self.view.backgroundColor = UIColor.blueColor() }, completion:{finished2 in UIView.animateWithDuration(5/3.0, animations: { self.view.backgroundColor = UIColor.purpleColor() }, completion:{finished3 in println("COLOR CHANGED") }) }) }) 

或者您可以使用关键帧animation,指定如下所示的中间帧。 relativeDuration应该是0到1之间的一个值,表示一个关键帧的相对持续时间。 例如,如果整个animation是3 seconds ,relativeDuration是(1/3) ,则该关键帧将animation3/3 = 1秒。

relativeStartTime类似于关键帧相对于整个animation的持续时间开始的相对时间。 例如,如果整个animation是3 seconds并且relativeStartTime是(1/3) ,则该关键帧将在1 second之后开始

 var duration = 5.0; var relativeDuration = 1.0/3; UIView.animateKeyframesWithDuration(duration, delay: 0, options: nil, animations: { UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: relativeDuration, animations: { self.view.backgroundColor = UIColor.yellowColor() }) UIView.addKeyframeWithRelativeStartTime(relativeDuration, relativeDuration: relativeDuration, animations: { self.view.backgroundColor = UIColor.blueColor() }) UIView.addKeyframeWithRelativeStartTime(2 * relativeDuration, relativeDuration: relativeDuration, animations: { self.view.backgroundColor = UIColor.purpleColor() }) }, completion:nil); 

对,因为这是一个属性的一个变化。 你需要做出这三个连续不同的animation。 首先生成黄色; 当这一切结束时,现在将一个全新的animation变成蓝色; 然后制作一个全新的animation到紫色。

链接最简单的方法是将每个新的animation放入前一个animation的完成处理程序中。 像这样(你将需要改变一些其他的东西,因为我拒绝写函数和variables以大写字母开头的代码):

 @IBAction func press(sender: AnyObject) { UIView.animateWithDuration(5.0/3.0, animations: { self.background.backgroundColor = UIColor.yellowColor() }, completion:{(Bool) in UIView.animateWithDuration(5.0/3.0, animations: { self.background.backgroundColor = UIColor.blueColor() }, completion:{(Bool) in UIView.animateWithDuration(5.0/3.0, animations: { self.background.backgroundColor = UIColor.purpleColor() }, completion:{(Bool) in println("COLOR CHANGED") }) }) }) } 

在iOS 8上,还有一种更优雅(但更难)的方式,即使用关键帧animation。 但要开始,我会build议你先做简单的方法!