在SwiftUI应用中实现暗模式切换 [英] Implement dark mode switch in SwiftUI App

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

问题描述

我目前正在我的应用程序中进入暗模式.虽然由于我的SwiftUI基础,暗模式本身并没有太大的麻烦,但我仍在努力选择独立于系统ColorScheme来设置ColorScheme的选项.

I'm currently looking into Dark Mode in my App. While Dark Mode itself isn't much of a struggle because of my SwiftUI basis i'm struggling with the option to set the ColorScheme independent of the system ColorScheme.

我在苹果的人机界面指南中找到了这一点,我想实现这一点特征. (链接:人机界面指南)

I found this in apples human interface guidelines and i'd like to implement this feature. (Link: Human Interface Guidelines)

有人知道如何在SwiftUI中做到这一点吗?我发现了一些指向@Environment的提示,但没有有关此主题的更多信息. (链接:最后一段)

Any idea how to do this in SwiftUI? I found some hints towards @Environment but no further information on this topic. (Link: Last paragraph)

推荐答案

单视图

要更改单个视图的配色方案(可以是应用程序的主要ContentView),可以使用以下修饰符:

Single View

To change the color scheme of a single view (Could be the main ContentView of the app), you can use the following modifier:

.environment(\.colorScheme, .light) // or .dark

.preferredColorScheme(.dark)

此外,您可以将其应用到ContentView,使整个应用变暗!

Also, you can apply it to the ContentView to make your entire app dark!

假定您未更改场景委托或@main

首先,您需要访问窗口以更改在UIKit中调用UserInterfaceStyle的应用程序colorScheme.

First you need to access the window to change the app colorScheme that called UserInterfaceStyle in UIKit.

我在SceneDelegate中使用了它:

private(set) static var shared: SceneDelegate?

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

然后,您需要将操作绑定到切换.因此,您需要一个模型.

Then you need to bind an action to the toggle. So you need a model for it.

struct ToggleModel {
    var isDark: Bool = true {
        didSet { 
            SceneDelegate.shared?.window!.overrideUserInterfaceStyle = isDark ? .dark : .light 
        }
    }
}

最后,您只需要切换开关即可

At last, you just need to toggle the switch:

struct ContentView: View {
     @State var model = ToggleModel()

     var body: some View {
         Toggle(isOn: $model.isDark) {
             Text("is Dark")
        }
    }
}


从应用程序的UIKit部分

每个UIView都可以访问该窗口,因此您可以使用它来将. overrideUserInterfaceStyle值设置为所需的任何方案.


From the UIKit part of the app

Each UIView has access to the window, So you can use it to set the . overrideUserInterfaceStyle value to any scheme you need.

myView.window?.overrideUserInterfaceStyle = .dark

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

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