Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode 11 -- SwiftUI's dark mode setup

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.enter image description here

I set my plist mode to be in dark mode for easier testing. enter image description here

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.

enter image description here

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?

like image 598
Craig Fisher Avatar asked Jun 10 '19 18:06

Craig Fisher


People also ask

How do I Preview dark mode in Xcode?

Xcode 11's Interface Builder also comes with a new feature for you to preview the screen in dark mode. Open any of your storyboards file, you should find the Interface Style option in the device menu. Click the dark mode icon to switch to the dark mode.

How do I use SwiftUI dark mode?

SwiftUI lets us detect whether dark mode or light mode is currently enabled using the colorScheme environment key. If you declare this using @Environment , you can refer to it in your views and they will automatically be reloaded when the color scheme changes.


1 Answers

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.

like image 153
l_priebe Avatar answered Sep 21 '22 23:09

l_priebe