2017-07-18 129 views
1

我现在有一个静态的背景色:动画背景颜色夫特3

self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0) 

我将如何代码超过几秒钟的设定数目创建一系列动画的颜色(例如每种颜色5秒)和然后返回到颜色循环的开始?

我已经试过以下...

self.backgroundColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0) 
UIView.animate(withDuration: 5.0, animations: {() -> Void in 
    self.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0); 
    self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0) 
}) 

...但这只是停留在过去的蓝色。

回答

2

你必须做一个嵌套动画

self.backgroundColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0) 
    UIView.animate(withDuration: 5.0, animations: {() -> Void in 
     self.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0); 
    }, 
    completion: { finished in 
     UIView.animate(withDuration: 5.0, animations: {() -> Void in 
      self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0) 
     }, completion: { finished in 
      //other color do the same 
     }) 

    }) 
+2

没错。 CoreAnimation在它们的当前值和动画块执行之后确定的最终值之间内插动画属性。 还要注意,如果没有使用block参数'finished',那么使用'completion {{in ...}''可能会更好。 – J2b

+0

上面的嵌套动画中的代码直接转到最后一种颜色(蓝色),并保留在那里,而没有以前颜色之间的动画。 – Bootfit

0

你可以试试这个:

let maxNumberOfRepeats = 10 
    var currentNumberOfRepeats = 0 
    Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { timer in 
     currentNumberOfRepeats = currentNumberOfRepeats + 1 
     if currentNumberOfRepeats == maxNumberOfRepeats { 
      timer.invalidate() 
      UIView.animate(withDuration: 1, animations: { 
       self.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0) //return to first color 
      }) 
     } else { 
      UIView.animate(withDuration: 1, animations: { 
       self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) //or any other random color 
      }) 
     } 
    }