Previewing the layout in dark mode
SwiftUI has built-in functionality to support dark mode. Xcode previews allow users to change from light to dark mode without adding any extra code within the view. This is done by changing the \.colorSheme
environment value in the preview.
In this section, we will create a simple app with a Text
view and then preview it in dark mode.
Getting ready
Create a new SwiftUI app named DarkModePreview
.
How to do it…
As of the time of writing this book, there is a bug in Xcode 11 that prevents dark mode previews of SwiftUI views that do not contain a navigation view. We need to enclose the content we want to view within a navigation view. The steps are as follows:
- Open the
ContentView.swift
file. - Add a
NavigationView
component to the body variable of theContentView
view:NavigationView { }
- Add a
Text
view inside theNavigationView
component. You can replace theText
view...