George
George

Reputation: 30391

Get update for light/dark mode theme change

I have a SwiftUI app, in which I have a SpriteKit scene. However, when changing between light and dark mode, the scene background does not change colour until the app is reopened.

This is not ideal, so I want to register when the light/dark mode appearance is changed. The colour in my assets has an "any" and a "dark" appearance.

Code inside updateUIView() within a UIViewRepresentable struct, which sets up the scene when it is linked with SwiftUI:

scene.backgroundColor = UIColor(named: "Color.Scene")!
uiView.presentScene(scene)

How do I achieve this? I am using iOS 13's system wide dark mode, so I do not want a solution of Notification Center because all I am looking to do is update the background according to the system settings.

Upvotes: 6

Views: 2797

Answers (1)

krjw
krjw

Reputation: 4450

You can use @Environment (\.colorScheme) var colorScheme: ColorScheme in your view and make the views body react to it:

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

    var body: some View {
        HStack {
            if self.colorScheme == .light { 
                // draw for light mode
            } else { 
                // draw for dark mode
            }
        }
    }
}

Upvotes: 5

Related Questions