I have a color asset catalog with my custom colors. Is there a way to get and display them in the application? Something like this
func getColorsFromAssetCatalog() -> [UIColor]? {
//Somehow return those colors
}
let colorsInCatalog = getColorsFromAssetCatalog()
for color in colorsInCatalog {
// Do something
}
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.
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)
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:
Colors.assetCatalogued
will not return any UIColor
sCaseIterable
for .allCases