swiftui

Change background color when dark mode turns on in SwiftUI


I've created a custom sheet in SwiftUI with the background color White .background(Color.white)

Now I want the background color to change to black when the user turns on the dark mode on iOS. But I can't find a dynamic color for background like Color.primary for colors of the text etc.

So is there any way to change the background color to black when dark mode turns on?


Solution

  • Here is possible approach (for any color)

        struct ContentView: View {
            @Environment(\.colorScheme) var colorScheme
        
            ...
            var body: some View {
        
                // ... to any view
                .background(colorScheme == .dark ? Color.black : Color.white)
        
            }
       }