简体   繁体   English

SwiftUI:在设备上测试时未检测到暗模式

[英]SwiftUI: Dark mode not detected when testing on device

I'm am trying to achieve dark mode within my iOS application using SwiftUI: simple test would be to change the background colour.我正在尝试使用 SwiftUI 在我的 iOS 应用程序中实现暗模式:简单的测试是更改背景颜色。

I have set up my colour set as seen below:我已经设置了我的颜色集,如下所示: 资产中的颜色集

ContentView.swift:内容视图.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)
  }
    
}

This doesn't work.这不起作用。 However, when forcing dark mode with .colorScheme(.dark) after .onAppear - it works.然而,迫使黑模式时.colorScheme(.dark).onAppear -它的工作原理。

When debugging with @Environment (\\.colorScheme) var colorScheme:ColorScheme it returns light , even though my iPhone is set to Dark Mode.使用@Environment (\\.colorScheme) var colorScheme:ColorScheme调试时,它会返回light ,即使我的 iPhone 设置为暗模式。

Have I missed something?我错过了什么吗?

I figured it out.我想到了。 Turns out User Interface Style was set to light in my Info.plist file - just delete it.原来用户界面样式在我的 Info.plist 文件中设置为light - 只需删除它。

用户界面风格

Target iOS 14.0目标 iOS 14.0

After more than one day on this, I finally found a solution.经过一天多的时间,我终于找到了解决方案。 If it can help someone out there ..如果它可以帮助那里的人..

My app needs to get the system ColorScheme at app launch and then it will be handle by the user in app settings.我的应用程序需要在应用程序启动时获取系统 ColorScheme,然后由用户在应用程序设置中处理。 And some Views are specifically force to .dark and some other to .light.一些视图特别强制为 .dark,而另一些则为 .light。 User Interface Style wasn't set in Info.plist, neither Appearance . User Interface Style未在 Info.plist 中设置,也未在Appearance

Same issue : @Environment (\\.colorScheme) var colorScheme:ColorScheme was returning always light !同样的问题: @Environment (\\.colorScheme) var colorScheme:ColorScheme返回总是很轻! What ever I was doing, or where ever the value was retrieved..我在做什么,或者在哪里检索到值..

After testing all internet's solution, here it is :在测试了所有互联网的解决方案后,这里是:

UITraitCollection.current.userInterfaceStyle

This is the only way to get the correct phone dark mode setting in my case.在我的情况下,这是获得正确手机暗模式设置的唯一方法。

Hope it will avoid to loose to much time on this.希望它会避免在这方面浪费太多时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM