Hex to UIColor April 19, 2016

Swift's UIColor methods require you to pass RGB values in a value / 255 format. I would prefer to work with Hex color, so whenever I get started with a new project one of the first things I do is add in this method to the global scope.

            func hexStringToUIColor (hex:String) -> UIColor {
        var cString: String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
        
        if (cString.hasPrefix("#")) {
            if let range = cString.range(of: cString) {
                cString = cString.substring(from: cString.index(range.lowerBound, offsetBy: 1))
            }
        }
        
        if ((cString.characters.count) != 6) {
            return UIColor.gray
        }
        
        var rgbValue: UInt32 = 0
        Scanner(string: cString).scanHexInt32(&rgbValue)
        
        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
      }
          

And then make calls throughout the project like this:

            
      let blueColor = hexStringToUIColor("#00A0B0")
      let redColor = hexStringToUIColor("#CC333F")
    
          

That's it! Have fun and #CompileSwift.