Thursday, February 21, 2019

Use Hex code to color string Swift

In Swift, to color string we use.
label.textColor = UIColor.blueColor()
This way just has some base color, put cursor after dot at UIColor. And press Ctrl+Space bar to see colors drop down from list. Not many color to use.
If want another color, we can use RGB like this.
label.textColor =UIColor(red: 1, green: 0.4, blue: 1, alpha: 1)
This way not easy to use, if we want to use Hex code color like "#a1caf1", use function below.
func hex (hex:String) -> UIColor {
        var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString
       
        if (cString.hasPrefix("#")) {
            cString = cString.substringFromIndex(cString.startIndex.advancedBy(1))
        }
       
        if ((cString.characters.count) != 6) {
            return UIColor.grayColor()
        }
       
        var rgbValue:UInt32 = 0
        NSScanner(string: cString).scanHexInt(&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)
        )
    }
When want to color something, call it like this.

view.backgroundColor = hex("#a1caf1")

No comments:

Post a Comment