gpt4 book ai didi

ios - 在SwiftUI中手动设置亮/暗模式并保存用户选择

转载 作者:行者123 更新时间:2023-12-01 17:35:32 25 4
gpt4 key购买 nike

我找到了一种在swiftui应用程序中另一个线程中手动设置亮/暗模式的解决方案,在这里找到https://stackoverflow.com/a/58476468/11698443,它通常可以工作,但是有两个问题。

  • 用户选择不是永久保存的。
  • 我希望默认选择为暗模式,因此无论用户将系统设置为亮模式还是暗模式,该应用程序最初都会以暗模式显示。

  • 目前,此实现存在一些问题,因为如果用户在灯光模式下打开应用并按下切换开关。他们第一次按下开关不会执行任何操作。他们将不得不再按两次开关才能触发didSet,以使应用进入黑暗模式,即使如此,选择也将无法保存。

    其他一些线程询问暗模式的实现,但是大多数线程处理UIKit,而我上面链接的线程是我可以在swiftui中正常工作的唯一解决方案。是否可以修改该解决方案以解决我提出的两个问题?

    最佳答案

    这是可能的方法(草率,您可以在SO属性包装器上找到默认值,并将其用于更好的样式,但是实现目标的想法是相同的)

    经过Xcode 11.4 / iOS 13.4测试

    class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    private(set) static var shared: SceneDelegate?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    Self.shared = self

    let contentView = ContentView()

    if let windowScene = scene as? UIWindowScene {
    let window = UIWindow(windowScene: windowScene)

    // restore from defaults initial or previously stored style
    let style = UserDefaults.standard.integer(forKey: "LastStyle")
    window.overrideUserInterfaceStyle = (style == 0 ? .dark : UIUserInterfaceStyle(rawValue: style)!)

    window.rootViewController = UIHostingController(rootView: contentView)
    self.window = window
    window.makeKeyAndVisible()
    }
    }

    ...
    }


    struct ContentView: View {
    var body: some View {
    // manipulate with style directly in defaults
    Toggle(isOn: Binding<Bool>(
    get: { UserDefaults.standard.integer(forKey: "LastStyle") !=
    UIUserInterfaceStyle.light.rawValue },
    set: {
    SceneDelegate.shared?.window!.overrideUserInterfaceStyle = $0 ? .dark : .light
    UserDefaults.standard.setValue($0 ? UIUserInterfaceStyle.dark.rawValue : UIUserInterfaceStyle.light.rawValue, forKey: "LastStyle")
    }
    )) {
    Text("is Dark")
    }
    }
    }

    关于ios - 在SwiftUI中手动设置亮/暗模式并保存用户选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61142948/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com