SwiftUI Preview 中的深色模式在 Xcode 11.4 中没有深色背景 [英] Dark mode in SwiftUI Preview doesn't have a dark background with Xcode 11.4

查看:28
本文介绍了SwiftUI Preview 中的深色模式在 Xcode 11.4 中没有深色背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有同样的问题,在深色模式下预览时 Xcode (11.4) 不显示深色背景?

Does anyone have the same problem, that Xcode (11.4) doesn't show a dark background, when previewing in dark mode?

重现步骤:

1) 创建一个新项目,一个Single View App

1) Create a new project, a Single View App

2) 将 .environment-modifier 添加到预览中:

2) Add the .environment-modifier to the preview:

Group {
    ContentView()
        .environment(\.colorScheme, .light)
    ContentView()
        .environment(\.colorScheme, .dark)
}

你得到这个结果:

推荐答案

试试这个:

@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
        }
    }
}

然后

yourView()
.environment(\.colorScheme, .dark)
                    .darkModeFix()

这篇关于SwiftUI Preview 中的深色模式在 Xcode 11.4 中没有深色背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆