[英]Dark mode in SwiftUI Preview doesn't have a dark background with Xcode 11.4
Does anyone have the same problem, that Xcode (11.4) doesn't show a dark background, when previewing in dark mode?有没有人有同样的问题,Xcode (11.4) 在深色模式下预览时不显示深色背景?
Steps to reproduce:重现步骤:
1) Create a new project, a Single View App
1) 创建一个新项目,一个
Single View App
2) Add the .environment
-modifier to the preview: 2) 将
.environment
添加到预览中:
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.不推荐在环境中设置
\\.colorScheme
,因此请改用.preferedColorScheme
修饰符。 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).正如在类似问题中提到的m-reza-f ,这是 Xcode 中的一个错误(在发布此答案时它仍然处于活动状态)。
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:我要补充的是,您可以简单地将
PreviewProvider
中的previews
代码包装在NavigationView
,而不是将您的实际body
代码包装在NavigationView
,以获得相同的结果:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.