Themes in SwiftUI App

Rajesh Budhiraja
6 min readJul 23, 2023

This is not uncommon to see multiple themes in apps. The theme here simply means the look and feel of the app. Depending upon how much flexibility we want to give users we can let them choose primary and secondary colours as well as fonts. Generally, it’s better to give users pre-defined themes as those themes will be tested by you and you will know what works and what just won't.

Let’s see how can we build this in the SwiftUI app. First of all, we will be defining things that we want to vary with themes. For our use case, it’s just colours. If you want to change fonts as well then you need to register all of the supported fonts.

import SwiftUI

protocol Theme {
var primaryColor: Color { get }
var secondaryColor: Color { get }
var backgroundColor: Color { get }
}

Now, let’s plan colours i.e. which colours will go in which theme. You can add hex codes of colours or create colour in Assets as shown in the screenshots below

Using a naming convention will make things easy for you when you try to use these colours. e.g. I have followed Theme(number)PrimaryColor and so on.

Once colours are defined, let’s create a theme manager. Since our entire app will oblige to themes selected by us we need to pass it to all views. We can do this by creating an environment object or singleton instance.

--

--