SwiftUI Image not switching to dark mode when created using UIImage

Solution 1:

This happens when the SwiftUI Image is initialized using an UIImage (seems to be a static initialization with no further observation of the original UIImage).

Workaround: The view can be informed to redraw manually, when using the colorScheme environment variable. Even when it seems to be unused in your later code.

This is pretty useful, if you need to consume UIImages from a shared UIKit/SwiftUI codebase.

In your example:

struct ContentView: View {

    // This is required for the automatic re-creation of the view
    // (and thus updating the Image with the appropriate appearance
    // for the UIImage)
    @Environment(\.colorScheme) private var colorScheme // <- view get's notified

    var body: some View {
        HStack {
            VStack {
                Image("my-image")
                Text("Image")
            }

            VStack {
                Image(uiImage: UIImage(named: "my-image")!)
                Text("Image+uiImage")
            }
        }
    }
}

Be aware that this might lead to unneeded redrawing, so try to use SwiftUI Images first, as @Jan said.

Solution 2:

The workaround here is to use Image without using the UIImage constructor