How to get the light or dark mode version of a SwiftUI Color?
Asked Answered
W

3

9

How do I create a local variable with specifically the dark mode color in SwiftUI. I am trying to avoid specifying the color scheme of each view to be dark to get the dark mode color.

For example in UIKit, I can get the dark mode color with this code

let traitCollection = UITraitCollection(userInterfaceStyle: .dark)
let darkModeBlueUIColor = UIColor.systemBlue.resolvedColor(with: traitCollection)

I know I can convert from a UIColor, but I want to specify it only using SwiftUI so it works on all platforms.

let darkModeBlueSwiftuiColor = Color(darkModeBlueUIColor)

I would like to do something like this involving a helper function

let darkModeBlueColor = Color.blue.darkModeColor
Welcy answered 14/7, 2021 at 0:42 Comment(0)
A
3

To draw color for specific color schema just use it in view body as

    Color("testColor")
        .colorScheme(.dark)   // << this !!

also if you use color variable then same can be done.

Acetaldehyde answered 14/7, 2021 at 4:50 Comment(1)
Unfortunately this results in a View, not specifically a Color. You can't use it where a colour is expected (e.g. foregroundColor).Forster
R
2

If anyone drops by this question, heres a solution that I've found and use:

extension UIColor {
    var light: UIColor {
        resolvedColor(with: .init(userInterfaceStyle: .light))
    }

    var dark: UIColor {
        resolvedColor(with: .init(userInterfaceStyle: .dark))
    }
}

I found it here.

You can initialize a SwiftUI Color this way:

if let primary = UIColor(named: "primary") {
    let dark = Color(primary.dark)
    let light = Color(primary.light)
}
Ropy answered 9/1 at 13:25 Comment(0)
B
1

A little late but I also ran into this problem. My extension is based on Mani's solution but directly uses SwiftUI Color instead of UIColor:

extension Color {
    var light: Self {
        var environment = EnvironmentValues()
        environment.colorScheme = .light
        return Color(resolve(in: environment))
    }

    var dark: Self {
        var environment = EnvironmentValues()
        environment.colorScheme = .dark
        return Color(resolve(in: environment))
    }
}

And is used like so:

Color.primary.light
Bucksaw answered 24/8 at 23:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.