Change background color when dark mode turns on in SwiftUI

To elaborate on the two existing answers, there are a couple of approaches to making the background change based on light or dark mode (aka colorScheme) depending on what you’re trying to achieve.

If you set the background color to white because that’s the default background color, and you want the system to be able to update it when the user switches to dark mode, change .background(Color.white) to .background(Color(UIColor.systemBackground)) (umayanga’s answer).

e.g.

// Use default background color based on light/dark mode

struct ContentView: View {
...
var body: some View {

    // ... to any view
    .background(Color(UIColor.systemBackground))

}

If you want to customize the color of a view based on the device being in light or dark mode, you can do this (from Asperi’s answer):

// Use custom background color based on light/dark mode

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

...
var body: some View {

    // ... to any view
    .background(colorScheme == .dark ? Color.black : Color.white)

}

Note that many SwiftUI views set their background color to .systemBackground by default, so if you’re using a ScrollView, List, Form, etc, they’ll use the default system background color and you won’t need to use .background unless you want to customize it.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)