Dealing with colours in the iOS project

- 3 mins

Usefulness is in simplicity.

The problem

Just imagine, you got beautiful app mockups from the designer, with perfectly specified colours in RGB or hex format (or you only got colourful mockups and had to ask “Hey, what’s hex for this button?”). Surely some colours 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 colours in an elegant, clean, and easy to change way?

Hardcoding colours’ 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.

Swift

The approach that I particularly like is the widely known use of extensions for UIColor**:

Objective-C

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, Folks!

That’s all you need. This approach results in a clean and convenient way of using colour 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.

Aleksander Popko

Aleksander Popko

iOS & macOS Software Engineer

comments powered by Disqus
rss facebook twitter github youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora