I want to use my color assets from the assets catalog using color literals.
In UIKit
, we can directly use color literal is there any way to use color literals in SwiftUI
I have searched from Color initializer with UIColor
parameter but none found
You can use a Color
defined in Asset Catalog by passing the string name inside the init
.
So, if I have the "Background" color inside my Assets.xcassets
:
I will use:
let backgroundColor = Color("Background")
Alternatively if the color is defined in another Bundle
you can use:
Color(name: String, bundle: Bundle)
P.S. It's seem that Color Literals doesn't work with the Asset color's
Note: From Xcode 11 Beta 5, Color
has an initializer for this already and no need to implement it.
So you can use colorLiteral like this:
Color(#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1))
Or any other CGColor
, UIColor
(or NSColor
for macOS):
Color(.red)
I find it helpful when designing layouts where I need to find and adjust a color quickly to use this method.
I do this whenever I want to use the drag and drop style color literals in SwiftUI.
Later, I can go back and add the hard coded color to my color scheme simply by commenting out "//" the color literal line in my code which reveals the RGB for my selected color.
Hope that helps.
Quite possibly it came out earlier but I didn’t catch it.
To get the autocomplete to work, type this line into your code.
#colorLiteral()
Then the code will automatically place the literal in the code for you to make the selection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With