May 25, 2020

Swift Essentials - UIColor from Hex

While working on a past project, a requirement was to set the background colour of a button with a specified colour retrieved from a REST API endpoint. This colour was a HEX string value in the format #FF0000.

Unfortunately, UIKit has no UIColor constructor that receives a colour in the Hex format, so I needed to implement a way to achieve this. Firstly we need to understand what colour in the Hex format is. Hex is short for hexadecimal and represents a number using a radix of 16. The string is comprised of 3 numbers representing the red (R), green (G) and blue (B) components of a colour. RGB colour components range from 0-255 in decimal representation.

For example, in the string #FF00CC, # specifies that this string is hexadecimal. Then, the first 2 bytes represent the red component, the next 2 bytes represent green, and the last 2 bytes represent blue.

Let’s write an UIColor extension that creates a constructor that receives a colour in hexadecimal format and creates an instance of UIColor from it.