使用Swift实现UIView背景颜色的动画效果

23

我想要以随机颜色为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背景看起来就像是一个随机的彩虹。

1个回答

50

只需将动画放在 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)
}

最新的Swift语法:self.view.backgroundColor = UIColor(red: red, green: green, blue: blue, alpha: alpha) - SoftDesigner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接