1

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
3
  • Please can you show the code that you tried. Thanks Commented Jan 23, 2023 at 14:00
  • Do you have a light and dark mode colour defined inside the primary color in you assets catalog? Commented Jan 23, 2023 at 14:07
  • 1
    @Fogmeister .primary is the built-in color in SwiftUI which is white in dark mode and black in light mode. I also have another color define either in light and dark in assets catalog. But don't really know how to access specific one (light or dark) in code. Commented Jan 23, 2023 at 14:10

1 Answer 1

2

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.