struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView().environment(\.colorScheme, .dark)
}
}
I am using the above code to achieve dark mode on my demo project but its not working.
Any help or insight would be really appreciated.
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
}
}
}