Swift:我怎样才能每秒随机改变背景颜色?

时间:2016-02-20 09:31:42

标签: ios arrays swift random nstimer

下面的代码为我提供了颜色数组中的随机背景颜色,每次打开应用程序时,都不会每秒都改变颜色。我在这里做错了什么?

import UIKit

class ViewController: UIViewController {

var timer = NSTimer()

func randomColorGenerator() -> Int{
    let randomColor = Int(arc4random_uniform(4))
    return randomColor
}

override func viewDidLoad() {
    super.viewDidLoad()
    let colors = [
        UIColor(red: 233/255, green: 203/255, blue: 198/255, alpha: 1),
        UIColor(red: 38/255, green: 188/255, blue: 192/255, alpha: 1),
        UIColor(red: 253/255, green: 221/255, blue: 164/255, alpha: 1),
        UIColor(red: 235/255, green: 154/255, blue: 171/255, alpha: 1),
        UIColor(red: 87/255, green: 141/255, blue: 155/255, alpha: 1)
    ]

     timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("randomColorGenerator"), userInfo: nil, repeats: true)

    let randColor = ViewController().randomColorGenerator()
    self.view.backgroundColor = colors[randColor]
}

2 个答案:

答案 0 :(得分:4)

试试这段代码:

import UIKit

class ViewController: UIViewController {
    var timer: NSTimer!

    func setRandomBackgroundColor() {
        let colors = [
            UIColor(red: 233/255, green: 203/255, blue: 198/255, alpha: 1),
            UIColor(red: 38/255, green: 188/255, blue: 192/255, alpha: 1),
            UIColor(red: 253/255, green: 221/255, blue: 164/255, alpha: 1),
            UIColor(red: 235/255, green: 154/255, blue: 171/255, alpha: 1),
            UIColor(red: 87/255, green: 141/255, blue: 155/255, alpha: 1)
        ]
        let randomColor = Int(arc4random_uniform(UInt32 (colors.count)))
        self.view.backgroundColor = colors[randomColor]
    }

    override func viewDidLoad() {
        super.viewDidLoad()

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

我更改的内容:我已将您的randomColorGenerator功能重命名为setRandomBackgroundColor。然后我使这个函数真正改变了颜色,而不仅仅是计算和返回一些随机索引。

其他一些细微更改:let randomColor = Int(arc4random_uniform(4))您可以使用UInt32(colors.count)代替硬编码常量4

var timer = NSTimer() - 您不需要初始化此计时器,以后不使用此初始值。只需声明变量类型即可:var time: NSTimer!

在您的初始示例中,您每秒计算一次随机索引,但您没有使用它然后实际设置背景颜色。

答案 1 :(得分:0)

@glyuck答案2019更新:

 override func viewDidLoad() {
    super.viewDidLoad()

    timer = Timer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(self.setRandomBackgroundColor), userInfo: nil, repeats: true)
    self.setRandomBackgroundColor()
}