I am working on my first project where I am trying to create a random color to a UILabel (when a button is pressed) that does not repeat itself twice in a row. I have read many questions and found codes that generates random numbers that does not appear twice in a row, however, when I "link" that random number to a UIColor and "link" that UIColor to a label the code no longer works. This code has no errors but it allows the same color to appear twice;
@IBOutlet var HelloWorld: UILabel!
@IBOutlet var MyButton: UIButton!
@IBAction func MyButton(sender: AnyObject) {
let randomNumber2 = Int(arc4random_uniform(5))
if randomNumber2 == 0 {
HelloWorld.textColor = UIColor.redColor()
}
else if randomNumber2 == 1 {
HelloWorld.textColor = UIColor.blueColor()
}
else if randomNumber2 == 2 {
HelloWorld.textColor = UIColor.yellowColor()
}
else if randomNumber2 == 3 {
HelloWorld.textColor = UIColor.orangeColor()
}
else if randomNumber2 == 4 {
HelloWorld.textColor = UIColor.blueColor()
}
Does anyone know how to generate a random color to a label that does not appear twice in a row?
You can use this Singleton
class
class ColorGenerator {
static let sharedInstance = ColorGenerator()
private var last: UIColor
private var colors: [UIColor] = [.redColor(), .blueColor(), .yellowColor(), .orangeColor(), .greenColor()]
private init() {
let random = Int(arc4random_uniform(UInt32(colors.count)))
self.last = colors[random]
colors.removeAtIndex(random)
}
func next() -> UIColor {
let random = Int(arc4random_uniform(UInt32(colors.count)))
swap(&colors[random], &last)
return last
}
}
The usage is pretty straightforward
Create a new file in your project ColorGenerator.swift
and paste the code above into it.
Anywhere in your code just write
ColorGenerator.sharedInstance.next()
to get a new random UIColor
.
That's it.