Swift – Custom UIColor extension, add custom colors.
In one of our previous tutorials we looked at extensions. In this one we will look at how we can use these to setup a custom UIColor extension to do the following:
- Add set custom colors to our Swift project
- Initialize a UIColor from hex
- Initialize a UIColor from RGB
First of all we have created a new single view application. Once done create a new Swift file and name it UIColor.
Open up UIColor then code it as follows:
import UIKit extension UIColor { // Setup custom colours we can use throughout the app using hex values static let seemuBlue = UIColor(hex: 0x00adf7) static let youtubeRed = UIColor(hex: 0xf80000) static let transparentBlack = UIColor(hex: 0x000000, a: 0.5) // Create a UIColor from RGB 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 ) } // Create a UIColor from a hex value (E.g 0x000000) convenience init(hex: Int, a: CGFloat = 1.0) { self.init( red: (hex >> 16) & 0xFF, green: (hex >> 8) & 0xFF, blue: hex & 0xFF, a: a ) } }
As we can see in the code:
- To create a UIColor from hex we can now use UIColor(hex: 0x000000)
- 0x indicates its the start of a hex number, the values after this are the hex value
- E.g Black in hex is #ff0000 so in our code to create black we use UIColor(hex: 0xff0000)
- We can also pass an optional parameter, a to set the alpha value of the color (the transparency)
- We can also create a UIColor from RGB without having to worry about dividing it by 255, E.g UIColor(red: 255, green: 0, blue: 0).
In the ViewController.swift viewDidLoad we can see our custom colors working by setting the background color as follows:
self.view.backgroundColor = UIColor.youtubeRed self.view.backgroundColor = UIColor.transparentBlack self.view.backgroundColor = UIColor.seemuBlue
This extension is very handy if you use certain colors consistently throughout your app. This way you don’t have to set it manually every time either in the storyboard or code. The benefits of this is you know the color is correct and if you want to change it you only have to do so in once place.
Also setting a color from hex is alot easier then RGB, you can copy the hex value straight out of Photoshop, or any other image editor and put it straight into your code!