kovxja
Last Updated: February 25, 2016
·
2.225K
· ashabanov
4379c9ef2f8ac46ae76c9ae2cc54961a

HEX colors in Swift

Yesterday I work on some ios8 project and I needed to use some colors for UI decorations different from the standard colors.
This is the code to get the color by it's hex value:

func getColorByHex(rgbHexValue:UInt32, alpha:Double = 1.0) -> UIColor {
        let red = Double((rgbHexValue & 0xFF0000) >> 16) / 256.0
        let green = Double((rgbHexValue & 0xFF00) >> 8) / 256.0
        let blue = Double((rgbHexValue & 0xFF)) / 256.0

        return UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha))
    }

Usage (lets set title color for UIButton):

signupButton.setTitleColor(getColorByHex(0xFF0000, alpha: 0.9), forState: .Normal)
Say Thanks
Respond

2 Responses
Add your response

17748
137cd1ce809553bc742004ff05634136

I had wrote a extension of UIColor:
https://github.com/DamonQin/CommonExtensionCollection-Swift.
It can also adapt to Hex Value like "#333" or "333".

Usage:
self.testButton.backgroundColor = UIColor.hexValue("323")
self.testButton.backgroundColor = UIColor.hexValue("#323")
self.testButton.setTitleColor(UIColor.hexValueWithAlpha("ffffff", alpha: 1.0), forState: UIControlState.Normal)

May you like this repo. Thx.

over 1 year ago ·
17750
4379c9ef2f8ac46ae76c9ae2cc54961a

Hey, I had a look at your extension - feels good) I like it. If I have chance, I definitely try your code for incoming projects.

over 1 year ago ·