Xcode 11 — SwiftUI's dark mode setup

╄→尐↘猪︶ㄣ 提交于 2019-12-10 03:52:25

问题


Okay. I know this shouldn't be rocket science. I can't seem to get dark mode working and I've read the documentation a few times. Hoping someone can pick out what I'm missing.

I have an named color in the asset catalog.

I set my plist mode to be in dark mode for easier testing.

My content view looks like this:

struct ContentView : View {
var body: some View {
    VStack {
        Text("Hello World")
        Text("Yo yo yo")
            .color(Color("darkModeColor"))
    }

}

}

No matter what I do, the color is ALWAYS of the "Any" appearance when it should be taking on the cyan color.

I know dark mode itself works because all the system semantic colors provide by apple are working just fine as you can see the "Hello World" text changed to white.

Any ideas what I'm missing or is anyone else running into this issue with Xcode 11 Beta 1?


回答1:


This is probably a bug in this beta release of Xcode 11. I tried the dark mode feature in a UIKit application and it is working perfectly using UIColor but the same color wouldn’t work using Color in SwiftUI. Hopefully this will be fixed in the next releases.


Update: This issue was fixed with Xcode 11 beta 3.




回答2:


A working (but quite verbose) solution we can use to overcome this current limitation is to extend Color with methods parameterised with the current color scheme as follows:

import SwiftUI

extension Color {

    static let lightBackgroundColor = Color(white: 1.0)

    static let darkBackgroundColor = Color(white: 0.0)

    static func backgroundColor(for colorScheme: ColorScheme) -> Color {
        if colorScheme == .dark {
            return darkBackgroundColor
        } else {
            return lightBackgroundColor
        }
    }
}

And in the views where you need to access these colors you would add an environment property for the color scheme and use it to retrieve the dynamic color:

import SwiftUI

struct ColoredView : View {

    @Environment(\.colorScheme) var colorScheme: ColorScheme

    var body: some View {
        Rectangle().fill(Color.backgroundColor(for: self.colorScheme))
    }
}

These colours defined in code work for Xcode previews as well as the simulator.




回答3:


You can change color scheme in your preview

struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.colorScheme, .dark)
    }
}

upd: and you can create any previews for light and dark modes

struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        Group {
            ContentView()
            ContentView().environment(\.colorScheme, .dark)
        }
    }
}


来源:https://stackoverflow.com/questions/56531508/xcode-11-swiftuis-dark-mode-setup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!