27

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?

Zain
  • 1,569
  • 1
  • 13
  • 19

4 Answers4

59

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")
    }
}
RPatel99
  • 7,448
  • 2
  • 37
  • 45
3

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))
3

How to detect dark mode

struct ContentView: View {
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        Text(colorScheme == .dark ? "In dark mode" : "In light mode")
    }
}

Source: https://www.hackingwithswift.com/quick-start/swiftui/how-to-detect-dark-mode

Steven Ogwal
  • 685
  • 6
  • 8
0

In XCode 13 :

@SwiftUI.Environment (\.colorScheme) var colorScheme:ColorScheme