簡體   English   中英

動畫UIView背景顏色迅速

[英]Animate UIView background color swift

我想用隨機顏色動畫UIView的背景。 這是我到目前為止所做的:

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背景看起來像一個隨機的彩虹。

只需將動畫放入getRandomColor

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM