Last Updated: September 09, 2019
·
4.948K
· tonyrain

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)

2 Responses
Add your response

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 ·

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 ·