Previewing a layout in dark mode
SwiftUI has built-in functionality to support dark mode. With Xcode previews, you can preview your views from light to dark mode with minimal effort by just changing the Xcode previews color scheme environment value.
In this recipe, we will add a dark mode to a minimalistic app with just a single Text
view.
Getting ready
Create a new SwiftUI app named DarkModePreview
.
How to do it
Since the inception of SwiftUI, there has been an issue with previews, where you cannot preview any view in dark mode except when the view is wrapped in a NavigationView
. Is this a feature or a bug? Hopefully, we get the answer in the next releases of SwiftUI.
In this recipe, we'll enclose a Text
view in a NavigationView
and preview it in light and dark mode. The steps are as follows:
- Open the
ContentView.swift
file. - Above the
body
variable, add an@Environment
variable that checks for the current color scheme:@Environment(\.colorScheme...