Jan
Jan

Reputation: 7654

SwiftUI Image not switching to dark mode when created using UIImage

I have a simple SwiftUI view where I create a Image view using a UIImage. The issue is that the Image created with the UIImage is not switching to the dark or light mode when the color scheme changes. It works correctly only if the entire view is reloaded. It works as expected if I use create the image directly with the image name.

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

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

The image itself is in a xcasset catalog

enter image description here

result is this (note the right image not changing when the appearance changes but only after restarting the app)

enter image description here

Upvotes: 6

Views: 2741

Answers (2)

Frederik Winkelsdorf
Frederik Winkelsdorf

Reputation: 4573

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.

Upvotes: 5

Jan
Jan

Reputation: 7654

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

Upvotes: 3

Related Questions