Not able to achieve dark mode using SwiftUI

This seems to be a bug in Xcode 11.0 beta. A temporary workaround is to wrap your content inside a NavigationView.

For example, the following code will not take effect in dark mode preview:

var body: some View {
  Text("Hello World")
}

But after wrapping the content in a NavigationView, dark mode preview works as expected:

var body: some View {
  NavigationView {
    Text("Hello World")
  }
}

Result:

enter image description here


Dark mode is half working in previews, it just forgets to draw the background.

The following workaround allows you to add .darkModeFix() to your ContentView() in your preview function. You can optionally add false as a parameter to switch off dark mode.

struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        Group {
            ContentView()
                .darkModeFix()
        }
    }
}

Just add the following somewhere in your project:

public struct DarkView<Content> : View where Content : View {
    var darkContent: Content
    var on: Bool
    public init(_ on: Bool, @ViewBuilder content: () -> Content) {
        self.darkContent = content()
        self.on = on
    }

    public var body: some View {
        ZStack {
            if on {
                Spacer()
                    .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
                    .background(Color.black)
                    .edgesIgnoringSafeArea(.all)
                darkContent.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity).background(Color.black).colorScheme(.dark)
            } else {
                darkContent
            }
        }
    }
}

extension View {
    public func darkModeFix(_ on: Bool = true) -> DarkView<Self> {
        DarkView(on) {
            self
        }
    }
}

It fixed the preview, but doesn't change my code

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
    }
}



struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            ZStack {
                Color.black.edgesIgnoringSafeArea(.all)
                ContentView().environment(\.colorScheme, .dark)

            }
            ContentView().environment(\.colorScheme, .light)
        }
    }
}