How I use UIAppearance to manage my app theme (Part 1/2)

In this first part I will explain the motivation, approach and define the objects I used.

In the second part I will dive deeper in the ThemeManager object that interacts with the UIKit API and how it is used in the app.

Motivation

Recently I add the possibility to change the theme of my application “TV Streams”, here is the final result:

Black, Light and Dark themes

Approach

In order to do it in a easy, maintainable and customizable way I used UIAppearance from UIKit.

This protocol has a collection of methods that allow you to change the appearance of several UIKit components, such as UINavigationBar, UIBarButtonItem and many others.

Moreover you can customize it for only change the appearance when the component is contained in another component type. Since views follow a tree structure you can choose to have a different appearance when an UIBarButtonItem is inside a UINavigationBar or a UIToolbar.

After reading the Apple documentation, I found to be useful the tutorial from Ray Wenderlich and this one from Abhimuralidharan. I also used the code in the Siesta sample application as a starting point.

Objects

I used the following objects to manage the theme:

  • ThemeName (enum): lists all the possible themes in a unique way;
  • Theme (protocol): defines all the properties needed for defining a theme;
  • LightTheme, DarkTheme, BlackTheme (structs): conform to the Theme protocol and implement the theme variation;
  • ThemeRepository (protocol): abstract how you can load and save a theme;
  • DefaultsThemeRepository (class): saves and loads the theme using the standard UserDefaults;
  • ThemeManager (class): returns the current theme and applies a different one, uses the repository to retrieve the current theme and save the one applied;