iosswiftswiftuicolor-scheme

How to programmatically get asset catalog color variants from in SwiftUI?


I have a color asset catalog in Xcode that defines a set of colors in both light ("Any") and dark ("Dark") variants. For example:

Picture of asset catalog color

I would like to programmatically enumerate the different colors, meaning, I'd like to get the color (Color("hkMagenta")) in both variants. Just getting it by name returns the "Any" variant.

How can I get the dark variant?

I had thought this would work:

ColorManager.hkMagenta.environment(\.colorScheme, .dark)

Unfortunately, no-go.

Cannot convert value of type 'some View' to expected element type 'Array.ArrayLiteralElement' (aka 'Color')

Any ideas?


Solution

  • Thanks to @Asperi for pointing out https://stackoverflow.com/a/66950858/12299030.

    TL;DR is, you can get the light and dark variants using UIColor.resolvedColor() like so:

    let c = Color(UIColor(named: "hkMagenta")!.resolvedColor(with: UITraitCollection(userInterfaceStyle: .dark)))