< How to detect the Reduce Motion accessibility setting | How to use decorative images to reduce screen reader clutter > |
Updated for Xcode 13.3
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 Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.