It’s quite often necessary to know the current color scheme of a device in order to modify the displayed content of an app. For example, you may want to change the background color of a view, the foreground color of a text, to show different images or different text. The reasons can be many. And all that depending on the light or dark color mode.
In SwiftUI it’s super fast to detect and determine the current color scheme using the colorScheme
environment key as follows:
1 2 3 4 5 6 7 |
struct ContentView: View { @Environment(\.colorScheme) var colorScheme … } |
The similarly named colorScheme
property indicates the current color scheme, and can be used to apply a different set of configuration in views.
For example, the following creates a text where its background and foreground colors depend on whether the light or dark mode is currently active. Determining that mode is just a matter of a simple condition:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
struct ContentView: View { @Environment(\.colorScheme) var colorScheme var body: some View { Text(“Hello world!”) .padding() .background(colorScheme == .light ? Color(UIColor.darkGray) : Color(UIColor.lightGray)) .foregroundColor(colorScheme == .light ? .white : .black) .font(.title) .cornerRadius(8) } } |