Something pretty simple, yet very useful. Just imagine, you got beautiful app mockups from the designer, with perfectly specified colors in RGB or hex format (or you only got colorful mockups and had to ask “Hey, what’s hex for this button?”). Surely some colors will occur many times in different mockups for the same app. Also, during the app development process, the UX team may change the app appearance many times. How we can define constant values of colors in an elegant, clean, and easy to change way?
Hardcoding colors’ values in views or view controllers is really a bad idea – maintaining the code, or changing it when mockups are updated can be unpleasant. What about using preprocessor macros? This is also far from perfect, as more debugging friendly solutions are available.
The approach that I particularly like is the widely known use of extensions (Swift) or categories (Objective-C) for UIColor:
In Objective-C we use the UIColor category. Just remember about prefixing to avoid category methods names clashes:
Take a look at differences between documentation in Objective-C and Swift files. If you still have doubts, read these two great blog posts:
That’s all you need. This approach results in a clean and convenient way of using color values in the project. Of course, this idea is not limited to UIColor – e.g. extensions or categories can be successfully used when dealing with other aspects, such as fonts.