Gabe12 Gabe12 - 7 months ago 42
Swift Question

Randomize color in XCode

I'm trying to randomize the text color of a label in XCode with some colors I already created, I've tried different ways and this is the closest I got.

override func viewDidLoad() {
super.viewDidLoad()

let color1 = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1)
let color2 = UIColor(red: 80/255, green: 1, blue: 200/255, alpha: 1)
let color3 = UIColor(red: 150/255, green: 80/255, blue: 1, alpha: 1)
let color4 = UIColor(red: 1, green: 80/255, blue: 80/255, alpha: 1)
let color5 = UIColor(red: 80/255, green: 1, blue: 80/255, alpha: 1)

var randomEight = arc4random_uniform(5)+1
var randomColor:String = String(format:"color%i", randomEight)

randomLabel.textColor = randomColor
}


However, the randomColor variable is a String and I can't transform it to a UIColor.

Answer

Put all of the colors in an array, then use randomEight as the index in the array to get the right color. Also, you may want to check the integer division to make sure you get the right colors.

let color1 = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1)
let color2 = UIColor(red: 80/255, green: 1, blue: 200/255, alpha: 1)
let color3 = UIColor(red: 150/255, green: 80/255, blue: 1, alpha: 1)
let color4 = UIColor(red: 1, green: 80/255, blue: 80/255, alpha: 1)
let color5 = UIColor(red: 80/255, green: 1, blue: 80/255, alpha: 1)

let colors = [color1, color2, color3, color4, color5]
var randomEight = Int(arc4random_uniform(colors.count))

randomLabel.textColor = colors[randomEight]