2015-12-20 30 views
10

UIView'in arka planını rastgele renkler ile canlandırmak istiyorum.Animate UIView arka plan rengi geçişi

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) 
    } 

} 

Ama sadece başında rastgele bir renk oluşturur ve benim animasyon bu tek renk kullanmak: burada ben şimdiye kadar yaptığım budur. Renkleri canlandırmanın bir yolunu bulmak istiyorum, bu yüzden UIVIew arka planı rastgele bir gökkuşağı gibi görünecekti.

cevap

20

Sadece animasyonu getRandomColor içine yerleştirin.

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

Evet, çok teşekkürler! tam istediğim gibi çalışır. –