Custom UIColor References in Swift

Branding is a priority with your app and colour scheme is a huge part of that. The default colours provided by Swift are really handy but what if you want to use your own branding colours?

You don’t want to have to type out a full colour reference each time like this

UIColor(red: 92.0/255.0, green: 38.0/255.0, blue: 92.0/255.0, alpha: 1.0)

Instead it would be much nicer to use a reference to a colour you only have to define once. Not to mention that if you then choose to change that colour later you only have to do it in one place.



The answer is an Extension!

Below is an extension which I include in the AppDelegate (after the closing bracket of the AppDelegate class) for all my apps. I can create as many custom colours as I need and they are all available to me throughout my app.


extension UIColor {
    class func customColor1() -> UIColor {
        return UIColor(red: 92.0/255.0, green: 38.0/255.0, blue: 92.0/255.0, alpha: 1.0)
    }
    class func customColor2() -> UIColor {
        return UIColor(red: 167.0/255.0, green: 192.0/255.0, blue: 27.0/255.0, alpha: 1.0)
    }
}

Now you simply use the following anywhere you like.

UIColor.customColor1()

You can update the colour at any point in the AppDelegate and your change will be consistent throughout your app.