Skip to content

Instantly share code, notes, and snippets.

@asarode
Last active September 18, 2024 20:50
Show Gist options
  • Save asarode/7b343fa3fab5913690ef to your computer and use it in GitHub Desktop.
Save asarode/7b343fa3fab5913690ef to your computer and use it in GitHub Desktop.
Generating random UIColor in Swift
func generateRandomColor() -> UIColor {
let hue : CGFloat = CGFloat(arc4random() % 256) / 256 // use 256 to get full range from 0.0 to 1.0
let saturation : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5 // from 0.5 to 1.0 to stay away from white
let brightness : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5 // from 0.5 to 1.0 to stay away from black
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1)
}
@trm36
Copy link

trm36 commented Oct 4, 2017

Thanks

@BlindDev
Copy link

BlindDev commented Nov 6, 2017

Thank you!

@brod-ie
Copy link

brod-ie commented Jan 11, 2018

Thanks! And if you prefer as a variable..

var randomColor: UIColor {
    let hue : CGFloat = CGFloat(arc4random() % 256) / 256 // use 256 to get full range from 0.0 to 1.0
    let saturation : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5 // from 0.5 to 1.0 to stay away from white
    let brightness : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5 // from 0.5 to 1.0 to stay away from black
                
    return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1)
}

@jjrscott
Copy link

Here's another version, but with optional parameters:

import UIKit

extension UIColor {
    
    static func random(hue: CGFloat = CGFloat.random(in: 0...1),
                       saturation: CGFloat = CGFloat.random(in: 0.5...1), // from 0.5 to 1.0 to stay away from white
                       brightness: CGFloat = CGFloat.random(in: 0.5...1), // from 0.5 to 1.0 to stay away from black
                       alpha: CGFloat = 1) -> UIColor {
        return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment