Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Using Color Set from Asset Catalog

Tags:

In SwiftUI, we can get a color from a color set in an asset catalog using:

extension Color {
    static let coral = Color("coral")
}

This requires stringly-typed names and gets quite tedious with many color sets. Is there another way to get color sets similar to how we use image literals to get images from an asset catalog? Or, just something less redundant.

If not, how are dynamic colors programmatically created in SwiftUI? For example, this is how it would be done in UIKit:

extension UIColor {
    static let dynamicColor = UIColor { $0.userInterfaceStyle == .dark ? .black : .white }
}
like image 403
JWK Avatar asked Jun 30 '19 10:06

JWK


People also ask

How does Swift code use color from assets?

To try this out, open your asset catalog, click the + button, then choose New Color Set from the menu that appears. Select the new color that got created – it will be a large white square – then press Alt+Cmd+4 to activate the attributes inspector so that you can customize it.

How do I change the color of an asset in Swift?

To create a color from our palette, we can do it directly by selecting the Assets. xcassets folder (or creating our own . xcassets folder for colors) in the project navigator (Project Navigator). Then we right click and select New Color Set.


2 Answers

I want to share an alternative way to define dynamic colors in Asset catalog, but no need to write tedious code like

Color("yellow")

1. Define your color in asset catalog as usual

enter image description here

2. In your code, find a place to define your color as a variable, in my case it'll be something like this:

extension Color {
    static let ui = Color.UI()
    
    struct UI {
         let yellow = Color("yellow")
    }
}

3. Finish

Use your color like this:

Text("Hello").background(Color.ui.yellow)

This only requires writing hard-coded color in your code for only 1 time.

like image 128
Johnny Avatar answered Nov 20 '22 18:11

Johnny


If not, how are dynamic colors programmatically created in SwiftUI? For example, this is how it would be done in UIKit:

this can be almost the same:

extension Color {
    static let dynamicColor = Color(UIColor { traitCollection in
        return traitCollection.userInterfaceStyle == .dark ? .black : .white
    })
}
like image 20
Asperi Avatar answered Nov 20 '22 18:11

Asperi