Programmatically detect dark mode in SwiftUI to display appropriate Image
You can use @Environment(\.colorScheme) var colorScheme: ColorScheme
in any view to get whether the device is in dark mode (.dark
) or light mode (.light
). Using that information, you can conditionally decide which image to show easily with a ternary operator.
For example, if you have an image named "lightImage" for light mode and "darkImage" for dark mode:
@Environment(\.colorScheme) var colorScheme: ColorScheme
var body: some View {
Button(action: {
foo()
}) {
Image(colorScheme == .light ? "lightImage" : "darkImage")
}
}
There's an @Environment
variable.
@Environment (\.colorScheme) var colorScheme:ColorScheme
Here's how I use it to fill an empty Rectangle:
Rectangle().fill(Color.fillColor(for: colorScheme))