0

I have a UILabel in a CustomCell and I would like to paint this label with a different color each time it is added to the table view.

let myBlue = UIColor(red: 62.0/255, green: 174.0/255, blue: 206.0/255, alpha: 1.0)
let myGreen = UIColor(red: 110.0/255, green: 186.0/255, blue: 64.0/255, alpha: 1.0)
let myRed = UIColor(red: 247.0/255, green: 118.0/255, blue: 113.0/255, alpha: 1.0)
let myYellow = UIColor(red: 255.0/255, green: 190.0/255, blue: 106.0/255, alpha: 1.0)

myLabel.backgroundColor = random(myBlue, myRed, myGreen, myYellow)

Any suggestions?

Thanks

fs_tigre
  • 10,650
  • 13
  • 73
  • 146
  • 2
    `myLabel.backgroundColor = [myBlue, myRed, myGreen, myYellow][Int(arc4random_uniform(4))]` or `[myBlue, myRed, myGreen, myYellow][arc4random_uniform(4).hashValue]` – Leo Dabus Feb 04 '16 at 01:47
  • 1
    if you want a method `func randomColor(colors: UIColor...) -> UIColor { return colors[Int(arc4random_uniform(UInt32(colors.count)))] } ` – Leo Dabus Feb 04 '16 at 02:04
  • 1
    Thanks a lot for your help. – fs_tigre Feb 04 '16 at 02:13

1 Answers1

1
myLabel.backgroundColor = random([myBlue, myRed, myGreen, myYellow])

 func random(colors: [UIColor]) -> UIColor {
         return colors[Int(arc4random_uniform(colors.count))]

 }
tnek316
  • 630
  • 1
  • 5
  • 16
  • You could use variadic arguments to accomplish exactly the syntax OP asked – Leo Dabus Feb 04 '16 at 02:03
  • I had to change the return value to `return colors[Int(arc4random_uniform(UInt32(myColors.count)))]` as @LeoDabus suggested. Here is how I did it. Thanks `let myColors = [myRed, myBlue, myGreen, myYellow]` `func random(colors: [UIColor]) -> UIColor { return colors[Int(arc4random_uniform(UInt32(myColors.count)))] }` `myLabel.backgroundColor = random(myColors)` – fs_tigre Feb 04 '16 at 02:12