Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode 11 - SwiftUI Preview Dark Mode [duplicate]

Tags:

In Xcode 11, we can enable dark mode when the app is running by toggling the Environment Overrides at the bottom of the debug area like so.

Environment Overrides

SwiftUI has the Canvas editor which generates live previews of the app as you are building your interface.

Is there a way where we can toggle to dark mode in these previews?

like image 586
Simon Avatar asked Jun 07 '19 05:06

Simon


People also ask

How do I Preview dark mode in Xcode?

Xcode 11's Interface Builder also comes with a new feature for you to preview the screen in dark mode. Open any of your storyboards file, you should find the Interface Style option in the device menu. Click the dark mode icon to switch to the dark mode.

How does SwiftUI detect dark mode?

SwiftUI lets us detect whether dark mode or light mode is currently enabled using the colorScheme environment key. If you declare this using @Environment , you can refer to it in your views and they will automatically be reloaded when the color scheme changes.

How do I change dark mode in SwiftUI?

To enable dark mode on a Simulator, go to Settings → Developer and toggle Dark Appearance.

How do I debug a SwiftUI preview?

You can attach the debugger to the app running in the preview by using Debug menu -> Attach to Process and choose your app. Now you can press Debug View Hierarchy button in the toolbar on the bottom of Xcode to run visual debugger.


1 Answers

You should have something like this at the bottom of the file that's being previewed. This is what Xcode uses to generate the preview:

#if DEBUG struct ContentView_Previews : PreviewProvider {     static var previews: some View {         ContentView()     } } #endif 

To change the preview to dark mode, you just need to specify a colorScheme:

static var previews: some View {     ContentView().colorScheme(.dark) } 

Or, you can even chose to preview light and dark mode at the same time:

static var previews: some View {     Group {         ContentView().colorScheme(.light)         ContentView().colorScheme(.dark)     } } 

I recommend watching the Introducing SwiftUI session for more examples of SwiftUI and how powerful the previews can be.

like image 175
Matthew Price Avatar answered Oct 11 '22 13:10

Matthew Price