Dark mode: SwiftUI bg color changes

Is there a way to set a dynamic background color in SwiftUI?

I’ve created a custom sheet in SwiftUI with a background color of white, using the following code:

.background(Color.white)

I’d like the background color to change to black when the user turns on the dark mode on iOS. Is there any way to achieve this?

Yes, you can use the colorScheme environment variable to dynamically change the background color based on the user’s chosen color scheme. Here is an example:

.background(Color("Background"))
.environment(\.colorScheme, colorScheme)

private var colorScheme: ColorScheme {
    return UIScreen.main.traitCollection.userInterfaceStyle == .dark ? .dark : .light
}

In this example, we are using a custom color named “Background” for the background color. We then use the colorScheme environment variable to set the color scheme based on the user’s chosen mode (light or dark). The colorScheme variable is determined using the userInterfaceStyle property of the traitCollection of the main screen.