How to Use Hex Color Values in Swift

How to Use Hex Color Values in Swift

6 June 2024 Stephan Petzl Leave a comment Tech-Help

When developing iOS applications, you might often need to use specific colors defined by hexadecimal values rather than relying on the predefined colors provided by UIColor. This guide will help you convert hex color values into UIColor objects in Swift.

Understanding Hexadecimal Color Values

Hexadecimal color values are a way of representing colors using a combination of six hexadecimal digits. Each pair of digits represents the red, green, and blue components of the color, respectively. For example, #ffffff represents white, where ff is the maximum value for red, green, and blue.

Creating a UIColor from Hex Values

To convert a hex color value to a UIColor object, you can create an extension for UIColor that includes an initializer to handle the conversion. Below is an example implementation:

extension UIColor {
   convenience init(red: Int, green: Int, blue: Int) {
       assert(red >= 0 && red = 0 && green = 0 && blue > 16) & 0xFF,
           green: (rgb >> 8) & 0xFF,
           blue: rgb & 0xFF
       )
   }
}

Using the UIColor Extension

With the above extension, you can easily create UIColor objects from hexadecimal values:

let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF)
let color2 = UIColor(rgb: 0xFFFFFF)

Handling Alpha Values

If you need to include an alpha component (transparency) in your color, you can extend the initializer to accept an alpha parameter:

convenience init(red: Int, green: Int, blue: Int, a: CGFloat = 1.0) {
    self.init(
        red: CGFloat(red) / 255.0,
        green: CGFloat(green) / 255.0,
        blue: CGFloat(blue) / 255.0,
        alpha: a
    )
}

convenience init(rgb: Int, a: CGFloat = 1.0) {
    self.init(
        red: (rgb >> 16) & 0xFF,
        green: (rgb >> 8) & 0xFF,
        blue: rgb & 0xFF,
        a: a
    )
}

Usage:

let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0.5)
let color2 = UIColor(rgb: 0xFFFFFF, a: 0.5)

Conclusion

By using the provided UIColor extension, you can easily convert hex color values to UIColor objects in Swift, allowing for greater flexibility and precision in your app’s design.

Streamlining Mobile App Testing with Repeato

While working on the aesthetics of your mobile application, it is equally important to ensure that the app functions correctly across various scenarios. This is where Repeato, a no-code test automation tool for iOS and Android, comes into play. Repeato allows you to create, run, and maintain automated tests for your apps efficiently.

Repeato leverages computer vision and AI to make test automation accessible even to non-technical team members, enabling developers to focus more on creating great products rather than on testing. For more details, check out our documentation or download the tool to get started.

Like this article? there’s more where that came from!