How to use hex color values in Swift

How to use hex color values in Swift

Learn how to use a HEX color string like β€œ#808080”(grey hex color code) in Swift with UIColor.

In this article, we will learn how to convert a HEX color value like β€œ#808080”(grey hex color code) to UIColor in Swift.

Why using hex values?

Most designers and color pickers are working with hex color values, but there is no builtin conversion from a hex string to UIColor. Let’s dive in and create a UIColor Swift extension that you can use to paste hex values directly into your swift code.

UIColor + HEX Extension

We will create a failable initializer, which will return nil if you specify a color in the wrong format.

The hex string should start with β€˜#’ character and have red, green, blue and alpha components.


extension UIColor {
    public convenience init?(hex: String) {
        let r, g, b, a: CGFloat
        
        guard hex.hasPrefix("#") else {
            return nil
        }
        
        let hexValue = hex.replacingOccurrences(of: "#", with: "")
        guard hexColor.count == 8 else {
            return
        }
        let scanner = Scanner(string: hexValue)
        var hexNumber: UInt64 = 0
        
        guard scanner.scanHexInt64(&hexNumber) else {
            return nil
        }
        r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
        g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
        b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
        a = CGFloat(hexNumber & 0x000000ff) / 255
        
        self.init(red: r, green: g, blue: b, alpha: a)
        return
    }
}

‍

Now you can easily use this function to initialize UIColor with a hex color value.



Related Posts

Create and edit colors. Easy.

We don’t just convert colors. Oh, no. We have the powerful color editing software you will ever need. If you need to pick a color from the screen, we can help you with that. If you need to generate a visually pleasing color palette, we can help you with that too. It’s not a problem, with Pikka.

Download now