Search code examples
iosarraysswiftrandomnstimer

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

Solution

  • Try this code:

    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()
        }
    }
    

    What I changed: I've renamed your randomColorGenerator function into setRandomBackgroundColor. Then I made this function to really change color instead of just calculating and returning some random index.

    Some other minor changes: let randomColor = Int(arc4random_uniform(4)) you can use UInt32(colors.count) instead of hardcoded constant 4.

    var timer = NSTimer() – you don't need to initialize this timer, you are not using this initial value later. It's enough to just declare variable type: var time: NSTimer!

    In your initial example, you were calculating random index each second, but you were not using it then to actually set the background color.