Search code examples
iosswiftuicolor

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


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
}

Solution

  • 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