Warm tip: This article is reproduced from serverfault.com, please click

SwiftUI: Using Color Set from Asset Catalog

发布于 2019-06-30 10:22:21

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 }
}
Questioner
JWK
Viewed
0
Asperi 2020-06-26 11:36:08

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