如何使用系统值选项实现配色方案切换?

fan*_*ber 0 swiftui ios-darkmode

我使用此线程上的指南在我的应用程序中实现了暗/亮模式切换。示例代码如下:

public struct DarkModeViewModifier: ViewModifier {

    @AppStorage("isDarkMode") var isDarkMode: Bool = true

    public func body(content: Content) -> some View {
        content
            .environment(\.colorScheme, isDarkMode ? .dark : .light)
            .preferredColorScheme(isDarkMode ? .dark : .light) // tint on status bar
    }
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

Picker("Color", selection: $isDarkMode) {
    Text("Light").tag(false)
    Text("Dark").tag(true)
}
.pickerStyle(SegmentedPickerStyle())
Run Code Online (Sandbox Code Playgroud)

如何通过添加一个System段来实现这一点?我想将 an 设置Int为默认设置,但我不知道如何将它与@AppStorage属性包装器联系起来。

以及如何在 SwiftUI 中观看系统模式更改生效?

dio*_*ogo 5

为此,您需要将用户的显示首选项从 Bool 存储到自定义枚举。然后,根据这个自定义枚举,您可以确定外观应该是深色还是浅色,并基于此应用显示首选项。

示例代码:

struct ContentView: View {
    enum DisplayMode: Int {
        case system = 0
        case dark = 1
        case light = 2
    }

    @AppStorage("displayMode") var displayMode: DisplayMode = .system

    func overrideDisplayMode() {
        var userInterfaceStyle: UIUserInterfaceStyle

        switch displayMode {
        case .dark: userInterfaceStyle = .dark
        case .light: userInterfaceStyle = .light
        case .system: userInterfaceStyle = UITraitCollection.current.userInterfaceStyle
        }

        UIApplication.shared.windows.first?.overrideUserInterfaceStyle = userInterfaceStyle
    }


    var body: some View {
        VStack {
            Picker("Color", selection: $displayMode) {
                Text("System").tag(DisplayMode.system)
                Text("Light").tag(DisplayMode.light)
                Text("Dark").tag(DisplayMode.dark)
            }
            .pickerStyle(SegmentedPickerStyle())
            .onReceive([self.displayMode].publisher.first()) { _ in
                overrideDisplayMode()
            }
        }.onAppear(perform: overrideDisplayMode)
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,你正在做的是

  • 为每个显示模式分配一个整数值(因此它可以存储在@AppStorage 中)
  • 设置选择器以在系统、深色和浅色之间进行选择,并将值保存在 UserDefaults 中
  • 通过打开@AppStorage 值来确定应用程序是否处于暗模式
  • 使用通过视图和子视图传递自定义暗模式配置 UIApplication.shared.windows.first?.overrideInterfaceStyle