Style management in Swift

Rutger Bresjer
Woost
Published in
2 min readJan 26, 2017

Promising to deliver working MVPs in one month means both product owners (the client) and developers (us) need to make quick decisions. This also often means designs are created and finetuned along the way. With only one month of development time, you don’t want to wait until designs are final.

In website development, we’ve got the great combination of HTML and CSS. In HTML, the semantic structure of the content is created. With CSS, styling is added, like fonts and colors. This means you can create a fully functional website with HTML, and apply styles with CSS later.

With Swift, you don’t have something similar to this. Normally you set fonts and colors for each component (labels, buttons, …) separately. When a client wants to change a font or a color, this means changing attributes in a lot of places.

To resolve this, I extend UIColor and UIFont with a couple of static variables which define app-wide styles.

Extending UIColor

First, I extend UIColor with some convenience initializers so I can initialize UIColor with hex colors:

Then, above the hex initializers, I extend UIColor with some static variables which represent the app’s color palette (thanks to Google for the Material Design color scheme):

This can even be more specific with static variables named e.g. viewBackground or navigationBarBackground. I like to try to keep the amount of different colors as small as possible.

Extending UIFont

Similar to UIColor, UIFont can be extended with some static variables too. First, I wrap the font styles in functions with size parameter. I use the great R.swift for accessing my resources, so the first part of the extension looks like this:

With these functions, I can easily swap the font family to another one. Then, I set up some static variables which return fonts in specific sizes. Note: it can be quite hard to minimize the amount of font styles!

Using the extensions

Now, it’s easy to use the styles throughout the app. For example, setting up a simple UILabel:

let label = UILabel()
label.font = .appBody
label.textColor = .appPrimary
label.text = "Your text here"

Whenever you want to change the color scheme, font families or font sizes, you only have to change the values in the extension!

Storyboard

I don’t use storyboards that often, but with some @IBInspectable-attributes, you can still make sure the styles in the extensions are consistently applied to your Interface Builder labels, buttons et cetera.

Unfortunately, @IBInspectables cannot be enums, but for example, add a couple of @IBInspectable booleans like isHeader and isBody and trigger a styling update in a didSet-observer.

--

--

Rutger Bresjer
Woost
Editor for

Product Strategist / Product Owner / Developer