Adding dark mode to a UIKit App
First, remember create a new branch for the changes, we can do that using Xcode or the git(1) command-line tool.
The basic support
iOS 13 introduced semantic colours, so UIKit already comes with support for automatic colour selection depending on the UserInterfaceStyle. So the simplest setup is to change our UIColor to semantic colours. For example:
| |
The alternative would be UIColor.secondarySystemBackground. You can check the UI Elements Colours on the Apple Documentation.
Allowing the user to set the theme
We could define themes and allow the user to choose between them. For example (Inside a ViewController):
| |
Storing the user preferences on UserDefaults
Let’s assume we are using an enum to represent the theme:
| |
We can get and set a theme key on the user’s defaults, by saving the raw value of the theme on the UserDefaults.
Reading from UserDefaults:
| |
Notice that defaults.integer(forKey:) will return 0 if it didn’t find a value for the “MyTheme” key.
Setting the value, assuming that we have the following enum for the theme style:
We can save the style in UserDefaults with the following code:
| |
Related topics/notes of interest
- Apple’s documentation on supporting dark mode in your interface
- UI Elements Colours on the Apple Documentation