Home > Net >  How to use dark mode color in light mode of SwiftUI App?
How to use dark mode color in light mode of SwiftUI App?

Time:01-24

I'm writing an app in SwiftUI, and have no trouble with normal UI. However, when a view's background is opposite to the app background color (e.g. use picture background), I need exactly what that color in the other color scheme. For example, Apple Music's lyrics are always in dark mode behavior (white text color, and white background color when hover) no matter what system color scheme is.

I know this Apple Music one can be solved by adding another color in Assets.xcassets, but it's just an example. What I need is to use light or dark of a color programatically. For those colors have different hex in different color schemes, how can I use its other side of color? Say, can I use the dark mode one of Color.primary in light mode?

I tried a lot solutions, but in vain. Firstly, I tried to attach .preferredColorScheme() to that view, but it eventually change color scheme of my whole app. Secondarily, I tried to convert a color into NSColor or UIColor, but there also no method defined in those two frameworks, at least I couldn't find. They all cannot work. How can I achieve this?

VStack {
    Text("Hello")      // where I want to use dark mode color (white one)
        .foregroundColor(.primary)
}
.background(Color.brown)
.preferredColorScheme(.dark)  // I tried here

CodePudding user response:

I'm not sure if there is a way to do this with SwiftUI.Color directly but we have an extension in our app like...

extension UIColor {
    public var lightVariant: UIColor {
        resolvedColor(with: UITraitCollection(userInterfaceStyle: .light))
    }
    public var darkVariant: UIColor {
        resolvedColor(with: UITraitCollection(userInterfaceStyle: .dark))
    }
}

And then you could use it with something like...

extension UIColor {
    public var asColor: Color {
        Color(self)
    }
}

To do...

UIColor(named: "primary").darkVariant.asColor

Or something like that.

Or from a Color to begin with...

UIColor(Color.primary).darkVariant.asColor

(You could create conveniences for this also.)

  • Related