2015-12-20 159 views
10

我想用隨機顏色爲UIView的背景設置動畫效果。 這是我到目前爲止已經完成:Animate UIView背景顏色swift

import UIKit 

class ViewController: UIViewController { 

    var timer = NSTimer() 
    var colours = UIColor() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     getRandomColor() 
     timerF() 

     UIView.animateWithDuration(2, delay: 0.0, options:[UIViewAnimationOptions.Repeat, UIViewAnimationOptions.Autoreverse], animations: { 
      self.view.backgroundColor = self.colours 

      }, completion:nil) 
    } 

    func timerF(){ 
     timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("getRandomColor"), userInfo: nil, repeats: true) 
    } 

    func getRandomColor(){ 
     let red = Float((arc4random() % 256))/255.0 
     let green = Float((arc4random() % 256))/255.0 
     let blue = Float((arc4random() % 256))/255.0 
     let alpha = Float(1.0) 
     colours = UIColor(colorLiteralRed: red, green: green, blue: blue, alpha: alpha) 
    } 

} 

,但它只是在開始生成一個隨機的顏色和我的動畫使用單一顏色。我想找到一種動畫顏色的方式,所以UIVIew背景看起來像隨機的彩虹。

回答

20

只要把動畫放在getRandomColor

func getRandomColor() { 
    let red = Float((arc4random() % 256))/255.0 
    let green = Float((arc4random() % 256))/255.0 
    let blue = Float((arc4random() % 256))/255.0 
    let alpha = Float(1.0) 

    UIView.animate(withDuration: 1.0, delay: 0.0, options:[.repeat, .autoreverse], animations: { 
     self.view.backgroundColor = UIColor(colorLiteralRed: red, green: green, blue: blue, alpha: alpha) 
    }, completion:nil) 
} 
+0

是的,非常感謝!完全像我想要的那樣工作。 –