samedi 20 février 2016

Swift: How can I change the background color randomly every second?

My code below gives me a random background color from my array of colors, every time I open the app, but does not change the color every second. What did I do wrong here?

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




Aucun commentaire:

Enregistrer un commentaire