Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically detect dark mode in SwiftUI to display appropriate Image

In Assets.xcassets, there is an ability to add additional images that will automatically switch based on the Appearances. This works well for static images but I'm trying to figure out how to do this for downloaded images.

Image Set

Is there a way to either set the dark mode version of an Image on init or is there a function in SwiftUI that will allow you to detect whether the current appearance is dark so that a different image URL can be served?

like image 460
Zain Avatar asked Jul 30 '19 20:07

Zain


People also ask

How does SwiftUI detect dark mode?

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.

How do I support dark mode in SwiftUI?

To enable dark mode on a Simulator, go to Settings → Developer and toggle Dark Appearance.

How can you tell dark mode in Swift?

Dark mode can be detected by using the userInterfaceStyle property on the current trait collection. When it's set to dark you know that the current appearance is set to dark.


1 Answers

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")
    }
}
like image 55
RPatel99 Avatar answered Oct 22 '22 00:10

RPatel99