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 }
}
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.
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.
I want to share an alternative way to define dynamic colors in Asset catalog, but no need to write tedious code like
Color("yellow")
extension Color {
static let ui = Color.UI()
struct UI {
let yellow = Color("yellow")
}
}
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.
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
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With