无法使用SwiftUI实现黑暗模式 [英] Not able to achieve dark mode using SwiftUI

查看:40
本文介绍了无法使用SwiftUI实现黑暗模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

以下解决方法允许您在预览功能中将 .darkModeFix()添加到 ContentView()中.您可以选择添加 false 作为参数以关闭暗模式.

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

这篇关于无法使用SwiftUI实现黑暗模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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