How to Use Assets Catalog Color Sets

SwiftUI: Using Color Set from Asset Catalog

If not, how are dynamic colors programmatically created in SwiftUI? For example, this is how it would be done in UIKit:

this can be almost the same:

extension Color {
static let dynamicColor = Color(UIColor { traitCollection in
return traitCollection.userInterfaceStyle == .dark ? .black : .white
})
}

backup

How to programmatically get asset catalog color variants from Xcode 13 in SwiftUI / Swift5.5?

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

How can I programmatically obtain all colors included in Color Assets catalog?

Currently there is no way to request the Asset Catalog to programmatically tell you what all assets it contains. i.e. there's no API, imho, that will let you fetch the color names (or other asset names) you have added in the Asset Catalog.

You can, ofcourse, fetch the color/asset if you already know the name.

Furthermore, the asset catalog compiles into Assets.car which is unreadable so attempts to read that file are also futile.

Anyways... coming back to your case, you would have to manually maintain some mechanism like an Enum to track the colors.


Solution:

  • Add a color to Asset Catalog; say named "WeirdOrange"
  • Use an Enum to maintain your custom color names, like:

    enum Colors: String {
    //... previous cases
    case weirdOrange = "WeirdOrange" //... now we add this one
    }
  • Use it in the app as:

    UIColor(named: Colors.weirdOrange.rawValue)

Example:

Lets fine-tune it a bit more for your purpose:

enum Colors: String, CaseIterable {
case funkyMunky = "FunkyMunky"
case weirdOrange = "WeirdOrange"
case popBlue = "PopBlue"
case murkyPoo = "MurkyPoo"

static var assetCatalogued: [UIColor] {
return self.allCases.compactMap { (colorCase) -> UIColor? in
return UIColor(named: colorCase.rawValue)
}
}
}

for color in Colors.assetCatalogued {
//Do something
print(color)
}

NOTE:

  • To run the example, either change the color names or add colors with the given names, else Colors.assetCatalogued will not return any UIColors
  • Used CaseIterable for .allCases
  • You would have to manually add/remove a case when adding/removing the related color asset

How to get color from Assets.xcassets?

You should use this init of UIColor

init?(named name: String) 

For example:

view.backgroundColor = UIColor(named: "Greeny")

And your name of Color in Assets must be the same as parameter in init



Related Topics



Leave a reply



Submit