Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 875
Amit Samant Avatar asked Aug 01 '19 10:08

Amit Samant


3 Answers

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:

enter image description here

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

like image 77
Giuseppe Sapienza Avatar answered Nov 20 '22 14:11

Giuseppe Sapienza


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))

preview

Or any other CGColor, UIColor (or NSColor for macOS):

Color(.red)
like image 10
Mojtaba Hosseini Avatar answered Nov 20 '22 14:11

Mojtaba Hosseini


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.

Using Easy Drag and Drop Color Literals with Xcode, Swift, SwiftUI


  • 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.


like image 8
Jim Bray Avatar answered Nov 20 '22 14:11

Jim Bray