< 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.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.