'Can I use color literals in SwiftUI
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
Solution 1:[1]
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
Solution 2:[2]
Easy Drag and Drop Color for Xcode Swift UI
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.
- Sorry I couldn't find any other way to describe this answer except for posting it this format *
Hope that helps.
UPDATE: As of Xcode 13.2.1
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.
Solution 3:[3]
You actually can use this hidden protocol to afford the same use of color literals for Color as is available for UIColor:
extension Color: _ExpressibleByColorLiteral {
public init(_colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float) {
self = Color(.sRGB, red: Double(red), green: Double(green), blue: Double(blue), opacity: Double(alpha))
}
}
Now you can use color literals for Color parameters.
Solution 4:[4]
Yes, SwiftUI has color literal.
The color literal is a parameter of the color struct. Use the following steps:
1. Type the word, Colo
2. Select Color literal from autocomplete
3. Now you can click on the color literal and select a color
Solution 5:[5]
You can use the getRed() method of UIColor to get the red, green, blue and alpha components and then use them to create a Color object. You could even create an extension that did it for you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Giuseppe Sapienza |
| Solution 2 | |
| Solution 3 | Noah Wilder |
| Solution 4 | |
| Solution 5 | Michael Salmon |


