我正在尝试在 SwiftUI、Xcode 12 和 iOS14 构建的应用程序中实现阅读暗模式。
我使用此键来确定它是否处于浅色或深色模式:@Environment(\.colorScheme) var colorScheme
我的测试设备设置为深色模式,但环境变量为阅读浅色模式。
我已经测试过删除应用程序、重新加载 XCode 并重新启动我的 Macbook Pro。
User Interface Style未使用,因为这是 iOS14。(SwiftUI:在设备上测试时未检测到深色模式)
奇怪的是,我的测试设备(iPhone 11 Pro)将非背景颜色的视图渲染得尽可能暗。所以唯一没有更新的是变量 colorScheme 本身。我不会以编程方式更改应用程序中任何位置的该值。
我还检查了我的 info.plist 在目标的构建设置中是否正确路由。我正在使用主应用程序的目标和小部件扩展的目标。
我缺少什么?
小智 10
在我的项目中,我发现@Environment(\\.colorScheme) var colorScheme获取软件的配色方案,而不是系统的配色方案。
所以当你手动更改软件本身的配色方案时,@Environment(\\.colorScheme) var colorScheme你无法再次获取手机的配色方案。
使用以下代码,它将获得手机的配色方案
\nlet currentSystemScheme = UITraitCollection.current.userInterfaceStyle\nRun Code Online (Sandbox Code Playgroud)\n需要注意的是userInterfaceStyle和 colorScheme不是同一类型,所以可能需要下面的代码来转换
func schemeTransform(userInterfaceStyle:UIUserInterfaceStyle) -> ColorScheme {\n if userInterfaceStyle == .light {\n return .light\n }else if userInterfaceStyle == .dark {\n return .dark\n }\n return .light}\nRun Code Online (Sandbox Code Playgroud)\n
我刚刚知道为什么
我@Environment(\.colorScheme) var colorScheme: ColorScheme在应用程序生命周期中阅读得太早了。
当我打开应用程序时,我会在应用程序完成初始化之前创建数据类。我在这个数据类中调用了@Environment(\.colorScheme) var colorScheme: ColorScheme。
一旦应用程序完成初始化,我就@Environment(\.colorScheme) var colorScheme: ColorScheme在视图上进行了测试.onAppear(),它按应有的方式工作
\n\n我希望当它在 Info.plist 中设置为 Dark 时它会显示为 Dark。每 \xe2\x80\xa6
\n
嗯...苹果的文档说枚举了用户设置选项(参见下面的完整快照):
\n/// The possible types of color schemes, like Dark Mode.\n///\n/// The color scheme enumerates the user setting options for Light or Dark Mode.\n/// It also provides the light or dark options for any particular view when the\n/// app wants to override the user setting.\n@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)\npublic enum ColorScheme : CaseIterable {\n\n case light\n\n case dark\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
4857 次 |
| 最近记录: |