Detecting dark mode in SwiftUI
Updated
SwiftUI lets us detect whether dark mode or light mode is currently enabled using the colorScheme environment key. If you declare this using @Environment, you can refer to it in your views and they will automatically be reloaded when the colour scheme changes.
For example, this will print either “In dark mode” or “In light mode” depending on the current colour scheme:
struct ContentView: View {
@Environment(\.colorScheme) var colorScheme
var body: some View {
Text(colorScheme == .dark ? "In dark mode" : "In light mode")
}
}
This should generally only be necessary for custom drawing – if you want to enable dark and light colours or dark and light images these can both be done using your asset catalog, and will also reload when the colour scheme changes.