- How to observe dark mode state in an iOS app
- How to react to changes in dark mode state in an iOS app

- 30,049
- 21
- 112
- 147

- 2,778
- 2
- 10
- 19
-
[Here](https://stackoverflow.com/questions/57279700/programmatically-detect-dark-mode-in-swiftui-to-display-appropriate-image/57280180#57280180) for how to do it with SwiftUI. – RPatel99 Mar 25 '20 at 15:22
2 Answers
UIKit has had UITraitCollection for a while now. Since iOS 9 you could use UITraitCollection to see whether the device supports 3D Touch (a sad conversation for another day)
In iOS 12, UITraitCollection got a new property: var userInterfaceStyle: UIUserInterfaceStyle
which supports three cases: light
, dark
, and unspecified
Since UIViewController inherits UITraitEnvironment, you have access to the ViewController's traitCollection
. This stores userInterfaceStyle
.
UITraitEnviroment also has some nifty protocol stubs that help your code interpret when state changes happen (so when a user switches from the Dark side to the Light side or visa versa). Here's a nice coding example for you:
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if self.traitCollection.userInterfaceStyle == .dark {
// User Interface is Dark
} else {
// User Interface is Light
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
// Trait collection has already changed
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
// Trait collection will change. Use this one so you know what the state is changing to.
}
}
-
-
@אוריorihpt You're right https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/dark-mode – Ori Dec 15 '21 at 10:21
-
You can use the following code to check for light, or dark mode in your project:
func viewDidLoad() {
super.viewDidLoad()
switch traitCollection.userInterfaceStyle {
case .light, .unspecified:
// light mode detected
case .dark:
// dark mode detected
}
}
You can also check for changes in the interface style:
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
let userInterfaceStyle = traitCollection.userInterfaceStyle // Either .unspecified, .light, or .dark
// Update your user interface based on the appearance
}
Just like in macOS since Mojave, you can define images for both light and dark mode in your asset catalogue so that those images will be used automatically:
Taken from here.

- 27,197
- 29
- 120
- 174