I usually use custom UIColors on iOS using extensions with Swift, but now with iOS 11/ Xcode 9 we can create Colors Sets. How can we use them?
Update - Tip
In Xcode 11 press command + shift + L , it will open a snippet , select last one like i showed in image drag and drop .
UIColor(named: "myColor")
Source: WWDC 2017 Session 237 —— What's New in MapKit
Caveat: Your project's Deployment Target needs to be set to iOS 11.0.
For your question if you can access color assets like the image using literal, as of Xcode 10.2 you can type in colorliteral
, then you can pick the color you want to use that is under your asset manager.
(short answer to the question update: there is UIColor(named: "MyColor") in Xcode 9.0)
Answering the original question:
it will translate to a color literal when looking at the source code:
#colorLiteral(red: 0, green: 0.6378085017, blue: 0.8846047521, alpha: 1)
You notice how the values of red, green and blue are different? It's because I defined them using Color Space Display P3
, but the colorLiteral is using Color Space sRGB
.
// iOS
let color = UIColor(named: "SillyBlue")
// macOS
let color = NSColor(named: "SillyBlue")
In case you experience a delay with colors loading in a Swift Package when using UIColor(named:)
:
The answers above are totally valid for a regular project but if you are using assets in a swift package, you can see a delay when loading the colors when you use UIColor(named: "example_name")
. If you use UIColor(named: "background", in: Bundle.module, compatibleWith: .current)
overload that is targeting the module, the colors load immediately without any delay.
Note: I experienced with Xcode 12.1.