【问题标题】:SwiftUI: Dark mode not detected when testing on deviceSwiftUI:在设备上测试时未检测到暗模式
【发布时间】:2020-05-07 18:41:01
【问题描述】:

我正在尝试使用 SwiftUI 在我的 iOS 应用程序中实现暗模式:简单的测试是更改背景颜色。

我已经设置了我的颜色集,如下所示:

ContentView.swift:

import SwiftUI

struct ContentView : View {

  @EnvironmentObject var session: SessionStore

  func getUser () {
      session.listen()
  }

  var body: some View {
    Group {
      if (session.session != nil) {
        VStack {
            WelcomeView()
            .background(Color("bg"))
            .edgesIgnoringSafeArea(.all)
        }
      } else {
        VStack {
            SigninView().transition(.move(edge: .bottom))
        }.frame(maxHeight: .infinity)
            .background(Color("bg"))
            .edgesIgnoringSafeArea(.all)
      }
    }.animation(.spring())
    .onAppear(perform: getUser)
  }
    
}

这不起作用。但是,当在 .onAppear 之后使用 .colorScheme(.dark) 强制使用暗模式时 - 它可以工作。

当使用@Environment (\.colorScheme) var colorScheme:ColorScheme 进行调试时,它会返回light,即使我的 iPhone 设置为深色模式。

我错过了什么吗?

【问题讨论】:

    标签: ios swift swiftui ios-darkmode


    【解决方案1】:

    我想通了。结果发现 用户界面样式 在我的 Info.plist 文件中设置为 light - 只需将其删除即可。

    【讨论】:

    • 谢谢!出于某种原因,我将该键设置为暗,这让我发疯了,试图弄清楚为什么亮模式不起作用。
    【解决方案2】:

    目标 iOS 14.0

    经过一天多的时间,我终于找到了解决方案。 如果它可以帮助那里的人..

    我的应用需要在应用启动时获取系统 ColorScheme,然后由用户在应用设置中处理。有些视图特别强制 .dark 和其他一些 .light。 User Interface Style 没有在 Info.plist 中设置,Appearance 也没有。

    同样的问题:@Environment (\.colorScheme) var colorScheme:ColorScheme 总是很轻松地返回!我在做什么,或者在哪里检索到值..

    在测试了所有互联网的解决方案后,这里是:

    UITraitCollection.current.userInterfaceStyle
    

    在我的情况下,这是获得正确手机暗模式设置的唯一方法。

    希望它能避免在这方面浪费太多时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 2014-03-22
      • 2017-12-16
      • 1970-01-01
      • 2021-07-13
      相关资源
      最近更新 更多