Swift 3 UIColor utilities : Random Hex color codes, Random UIColor

Simple  to use swift 3 functions which are very useful in development and testing.

1.Generating random UIColor in Swift 3: Function returns random UIColor each time

func randomUIColor(alpha:CGFloat!)-> UIColor
{
    return  UIColor.init(red:(CGFloat(arc4random_uniform(256))/255.0), green:CGFloat(arc4random_uniform(256))/255.0, blue: (CGFloat(arc4random_uniform(256))/255.0), alpha: alpha)
}

2.Random HEX Color code in Swift 3 : Function returns random 3 char Hex color code each time .

func randomHexColorCode() -> String{
    let a = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
    return "#".appending(a[Int(arc4random_uniform(15))]).appending(a[Int(arc4random_uniform(15))]).appending(a[Int(arc4random_uniform(15))])
}

3.UIColor from HEX Color code : Function takes in a 3 char hex code with or without # in string format and returns a UIColor.This function comes in handy to directly generate UIColor from hex code

func colorFromHexString(hexCode:String!)->UIColor{
    let scanner  = Scanner(string:hexCode)
    scanner.charactersToBeSkipped = CharacterSet(charactersIn: "$+#")
    var hex: CUnsignedInt = 0
    if(!scanner.scanHexInt32(&hex))
    {
        return UIColor()
    }
    let  r  = (hex >> 16) & 0xFF;
    let  g  = (hex >> 8) & 0xFF;
    let  b  = (hex) & 0xFF;
    
    return UIColor.init(red: CGFloat(r) / 255.0, green:  CGFloat(g) / 255.0, blue:  CGFloat(b) / 255.0, alpha: 1)
}

 

 

 

 

A pat on the back !!

Leave a Reply

Your email address will not be published. Required fields are marked *