How to use XCAssets colors of Xcode 9 in Interface Builder and code

Roland
3 min readAug 9, 2018

Xcode 9 allows us to define colors in XCAssets, which can be used from Interface Builder and from code. This is convenient and helps ensuring easy updating/changs in the future, since all colors will be defined in one place only.

Define colors in interface builder.

These colors can leverage the color picker from macOS which supports RGB, HEX, CMYK and more.

Use defined colors

Now that all colors are defined in one place, how do we use them?

Interface Builder

In order to use them from Interface Builder, simply select a view, button or other view object and open the Attributes Inspector in the Utility Sidebar. Select the color in the color-dropdown, which should list the colors we previously defined.

That’s it. Easypeasy.

use XCAssets colors in Interface Builder

Code

Unfortunately it’s currently not that convenient to reference XCAssets colors from code. The only way it will update correctly is to hardcode the name to the color name in XCAssets.

Hardcoded reference to XCAssets colors
In code we can hardcode the color.

UIColor(named: "c_warning")

However, this has the drawback, that the compiler will NOT warn us if we have a typo or if the color does not exist. Essentially the application will crash at runtime, which is – as we all know – poor design.

“Än Absturz zur Laufziit isch den abär gar nöd guät”
— as we would say in Swiss German

Drag & drop colors
So what should we do? Well, the Media Library inside the Utility Sidebar allows drag & drop of the colors into the code. Unfortunately this is NOT a reference to the colors in XCAssets, which means, that when we update the colors in XCAssets we’d need to drag & drop them again.

replace hard coded color references with the actual colors

Please remember that you might be able to avoid hard-coding colors by creating additional views (UITableViewCell, UICollectionViewCell) with different reuseIdentifier in the Interface Builder. This has another advantage since it will prevent mixing styles into your code and keep them inside the storyboards and .xib files.

I’ll update this article as I find a better way to deal with colors, but I wanted to aggregate this information for you, so you can save time searching about this. Let me know if you have a better solution/approach!

Sources

--

--

Roland

Software Engineer, UI/UX, video games, dogs, photography, www.skofgar.ch