Home > front end >  Xcode: Color from asset vs Color from hex
Xcode: Color from asset vs Color from hex

Time:08-28

I was just wondering if there is any severe advantage in using colors from assets rather than "generating" them programmatically.

Is there any downside to defining colors like:

let myColor = Color(red: 0.5, green: 0.5, blue: 0.5)

rather than having a color like this in the assets with the name "myColor" and accessing it like:

let myColor = Color("myColor")

Thanks!

CodePudding user response:

There is a slight disadvantage the second way: you can get the literal string name of the color set wrong. On the other hand, it's a lot easier to configure a color in complex ways, and of course to see it, in the asset catalog.

CodePudding user response:

It is harder to change your mind about the colors if you hardcode the RGB values.

Suppose Color(red: 0.5, green: 0.5, blue: 0.5) is the background color in your app's color scheme, and you have used this in 10 places in your code.

If you want to try out a different background color, you would need to find the 10 places you have written Color(red: 0.5, green: 0.5, blue: 0.5) and meant that as a background color, and change all those 10 places. That is a pain.

If you instead put the color in the asset catalog, all you need to do to change the color is to simply change the contents of the color in the asset catalog - no code changes needed.

Another disadvantage of hardcoding the RGB values, is that it is inconvenient to do different colors for dark mode. You'd need to get the @Environment(\.colorScheme), and then check like this:

colorScheme == .dark ? 
    Color(red: 0.8, green: 0.8, blue: 0.8) : 
    Color(red: 0.1, green: 0.1, blue: 0.1)

which doesn't look very nice at all.

By using an asset catalog name, all the information about dark mode and whatnot is in the asset catalog. You'd have less noise in your code.

  • Related