< How to detect the Reduce Motion accessibility setting | How to use decorative images to reduce screen reader clutter > |
Updated for Xcode 14.2
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 color scheme changes.
For example, this will print either “In dark mode” or “In light mode” depending on the current color 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 colors or dark and light images these can both be done using your asset catalog, and will also reload when the color scheme changes.
SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.