ios - 快速动画 UIView 背景颜色

标签 ios swift animation uiview colors

我想用随机颜色为 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)
}

关于ios - 快速动画 UIView 背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34383678/

相关文章:

ios - 使异步 alamofire 请求同步

ios - Swift 可编码,当 JSON 中缺少键时,类属性的默认值

javascript - 如何重新启动/重置 Jquery 动画

ios - 如何禁用 UINavigationBar 上的向右滑动手势?

ios - iPhone 。 tableViewController 的 setter/getter

ios - Heroku:运行我的应用程序的成本有多高?

ios - 以编程方式设置 Swift 元素的位置

swift - 在 Swift 中将 Array<Any> 转换为 Array<Int>

jquery - 在 CSS 中扩展边框而不向下推其他元素

iphone - iPhone sdk 中最简单的逐帧动画技术是什么?