Does anyone have the same problem, that Xcode (11.4) doesn't show a dark background, when previewing in dark mode?
Steps to reproduce:
1) Create a new project, a Single View App
2) Add the .environment
-modifier to the preview:
Group {
ContentView()
.environment(\.colorScheme, .light)
ContentView()
.environment(\.colorScheme, .dark)
}
You get this result:
Setting \\.colorScheme
in the environment is deprecated, so instead use the .preferedColorScheme
modifier. For example,
ContentView()
.preferredColorScheme(.dark)
As m-reza-f mentioned in a similar question , this is a bug in Xcode (which is still active as this answer is posted).
I'll add that instead of wrapping your actual body
code in a NavigationView
, you can simply wrap the previews
code in your PreviewProvider
in a NavigationView
instead, to achieve the same results:
struct ContentView_Previews: PreviewProvider {
Group {
NavigationView {
ContentView()
.environment(\.colorScheme, .light)
}
NavigationView {
ContentView()
.environment(\.colorScheme, .light)
}
}
}
try this:
@available(iOS 13.0, *)
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
}
}
}
}
@available(iOS 13.0, *)
extension View {
@available(iOS 13.0, *)
public func darkModeFix(_ on: Bool = true) -> DarkView<Self> {
DarkView(on) {
self
}
}
}
and then
yourView()
.environment(\.colorScheme, .dark)
.darkModeFix()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.