Swift : Creating themes with Programmatically UI

Raoni Valadares
3 min readApr 2, 2018

--

Hello there,

When you have to work on an app which has UI identity crisis and constantly changes, it can be very messy. So to avoid spending unnecessary time with re-work, a friend(Solli Moreira Honorio) and I decided to try something different to avoid problems using a mix of Programmatically UI + Factory pattern + Builder.

If you don't know what it is or why use Programmatically UI, beware: as a iOS developer, one day in your life you will be part of a big discussion about meaning of life, the universe and what is better to use: Xib's, Storyboard or Programmatically UI.

Some good links about it:

Base Structure

Here it is our initial view controller:

Basically UI elements have their attributes defined by closures:

private let topicLabel: UILabel = {...}()

At private func buildUI() we will set the view color, add elements and constraints to it.

The beginning of the problem

As more UI elements the view controller has, we will see problems like:

  • Repeated code;
  • A lot of points to do maintenance;
  • Zero reusability.
ViewController UI elements *v1

Imagine: the app is growing, more view controllers will appear, other demands with priority will arrive and our little problem begins to scale and this can be transformed in nightmare in a blink of an eye when an unexpected task arrives…

We need to change visual identity of the app, again!

Solution: Mix factory and builder pattern

Starting with our factory class and putting all default attributes of an UI element there.

And finally create our builder function.

UILabelFactory

And use it like this:

private let label = UILabelFactory(text: "example").build()

Adding flexibility with Builder pattern

And if some label needs a different attribute like font size, text color or number of lines?

UILabelFactory with flexibility to change attributes

Adding chain calls to configure your components with different attributes:

private let miniDescriptionLabel = UILabelFactory(text: "Lore lore...")
.numberOf(lines: 3)
.textColor(with: .blue).build()

ps: there are other ways to use builder pattern (ex: Label extensions and protocols).

And if you don't need to change attributes of the components?

We can take advantage of Enum + Init.

A simple example:

Enum + inits

Final result

So remember the *v1 of our ViewController UI elements?

We change from this:

ViewController UI elements *v1

to this:

ViewController UI elements *v2

What did we achieved here?

  • A cleaner code;
  • Reusability;
  • An easy and fast way to change app UI elements.

Thank you for your time and feel free to leave a feedback,

Cheers. o/

Full exemple: https://github.com/raonivaladares/code_ui_factory_demo_ios

Swift version: 4.0

--

--