Search code examples
iosswiftuilabeluicoloruibackgroundcolor

Choose UIlabel background Color from Array and then remove it from array. (swift)


I have 3 UiLabels onscreen. I have an array with colors e.g. red,green,blue. I want to set the background of each UiLabel to a a color in the array and then delete the Color from the array so no 2 UiLabels have the same Color.

I was trying to do something like this. it selects a random string in the array but then i cannot assign it to the uilabel because its not of type UIColor.

override func viewDidLoad() {
    super.viewDidLoad()


    let Colorarray = ["UIColor.redColor()", "UIColor.greenColor()", "UIColor.blueColor()"]


    let randomIndex = Int(arc4random_uniform(UInt32(Colorarray.count)))


    print(randomIndex)
    self.left.text = (Colorarray[randomIndex])


    self.left.backgroundColor =  (Colorarray[randomIndex])
    self.middle.backgroundColor = (Colorarray[randomIndex])
    self.right.backgroundColor = (Colorarray[randomIndex])



}

this was the second code i tried

var colorArray = [(UIColor.redColor(), "Red"), (UIColor.greenColor(), "Green"), (UIColor.blueColor(), "Blue")]

//random color
let randomIndex = Int(arc4random_uniform(UInt32(colorArray.count)))

//accessing color
var (color, name) = colorArray[randomIndex]
self.left.text = name
self.left.backgroundColor = color
let leftColorRemoval = (colorArray.removeAtIndex(randomIndex))
print(leftColorRemoval)

var (mcolor, mname) = colorArray[randomIndex]
self.middle.text = mname
self.middle.backgroundColor = mcolor
let middleColorRemoval = (colorArray.removeAtIndex(randomIndex))
print(middleColorRemoval)

var (rcolor, rname) = colorArray[randomIndex]
self.right.text = rname
self.right.backgroundColor = rcolor
let rightColorRemoval = (colorArray.removeAtIndex(randomIndex))
print(rightColorRemoval)

Solution

  • You can store an array of tuples that include both the actual UIColor and the string value. This makes it so you can provide any string value you want:

    let colorArray = [(UIColor.redColor(), "Red"), (UIColor.greenColor(), "Green"), (UIColor.blueColor(), "Blue")]
    

    Then, to access a random color:

    let (color, name) = colorArray[randomIndex]
    
    self.left.text = name
    
    self.left.backgroundColor = color
    ...
    

    It seems to me that your code doesn't actually remove random colors. Here's how you would actually do it (one of many ways):

    let random = { () -> Int in
        return Int(arc4random_uniform(UInt32(colorArray.count)))
    } // makes random number, you can make it more reusable
    
    let (leftColor, leftName) = colorArray.removeAtIndex(random()) // removeAtIndex: returns the removed tuple
    let (middleColor, middleName) = colorArray.removeAtIndex(random())
    let (rightColor, rightName) = colorArray.removeAtIndex(random())