SwiftUI Dark Mode Preview Tutorial

The previews are by default in light mode in SwiftUI. This can be changed to dark mode using an environment setting. In this tutorial the preview will be altered to dark mode and dark mode will also be enabled in the iOS simulator . SwiftUI requires Xcode 11 and MacOS Catalina, which can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIDarkModePreviewTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

struct ContentView: View {
    var body: some View {
            Text("Dark mode Preview")
        }
    }
}

To enable dark mode an environment value can be used. Change the ContentView_Preview struct to

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environment(\.colorScheme, .dark)
    }
}

At the current state of SwiftUI, The preview of dark mode only works if the views inside ContentView are embedded inside a navigation view. Change the code to

struct ContentView: View {
    var body: some View {
        NavigationView {
            Text("Dark mode Preview")
        }
    }
}

Now the preview will be displayed in dark mode.

Enabling dark mode in the preview will not enable it in the iOS Simulator at startup. To do this add the environment value to the navigation view.

struct ContentView: View {
    var body: some View {
        NavigationView {
            Text("Dark mode Preview")
        }.environment(\.colorScheme, .dark)
    }
}

Build and Run the project to see dark mode enabled in the iOS simulator.

The source code of the SwiftUIDarkModePreviewTutorial can be downloaded at the ioscreator repository on Github.