Is it possible to change the color of a button with a text label using a random generator ?

I am confused on whether I can change the color of a button by a label. The label will determine what color the button will be from using a random color generator in code.

Answered by Claude31 in 192086022

Call myButton.setTitleColor(UIColor.blue, forState: .Normal) each time you want to change the color.


You could put it in the didSet of the label.


To generate random color, define colore with RGB : compute 3 random numbers betwwen 0...255: redRandom, greenRandom, blueRandom

and call

setTitleColor(UIColor(red: redRandom/255.0, green: greenRandom/255.0, blue: blueRandom255.0), forState: UIControlState.Normal)

Do you want to change the background color ?


Use : button.backgroundColor = UIColor.blue


Then test the label content to select the color.

No. I just want to change the text label color. When the text label color randomly changes, one of the UIbuttons that I have on the User Interface will change to the same color of the text label. Ex... Simon says turn left, The person will turn left because it is Simons instructions.

OK. So use setTitleColor


myButton.setTitleColor(UIColor.blue, forState: .Normal) // if you want this color for normal state

So is it possible to have the Button color change randomly ? Using that code only allows me to change the color once.

Accepted Answer

Call myButton.setTitleColor(UIColor.blue, forState: .Normal) each time you want to change the color.


You could put it in the didSet of the label.


To generate random color, define colore with RGB : compute 3 random numbers betwwen 0...255: redRandom, greenRandom, blueRandom

and call

setTitleColor(UIColor(red: redRandom/255.0, green: greenRandom/255.0, blue: blueRandom255.0), forState: UIControlState.Normal)

Thank you! I appreciate the help.

Don't know if this helps or if you even need it, but I use this in one of my practice projects to get random colors. You can also use the rFrac() to just get random fractions.


public struct Math {
    private static var seeded = false
  
    static func rFrac() -> CGFloat {
        if !Math.seeded {
            let time = Int(Date().timeIntervalSinceReferenceDate)
            srand48(time)
            Math.seeded = true
        }
        return CGFloat(drand48())
    }
  
    static func rndColor() -> UIColor {
        return UIColor(red: rFrac(), green: rFrac(), blue: rFrac(), alpha: 1.0)
    }
}


Then call it like this:

color = Math.rndColor()
Is it possible to change the color of a button with a text label using a random generator ?
 
 
Q