Search code examples
swiftuicolorios-darkmode

How to get explicitly light or dark color from ColorSet?


Using UIColor.init(named: "customColorSet") it is no problem to get color from ColorSet which matches the current userInterfaceStyle.

However, how can I get a specific color from the color set, e.g. the light or dark color?

I tried using UIColor.init(named: "customColorSet", in: nil, compatibleWith: UITraitCollection(userInterfaceStyle: .light)) but it doed not seem to work, because still the color matching the current userInterfaceStyle is returned (dark in my case).


Solution

  • You can use UIColor.resolvedColor(with:)

    Tested:

    let color = UIColor(named: "Color")?.resolvedColor(with: UITraitCollection(userInterfaceStyle: .light))
    let rgb = color!.cgColor.components