iOS 13 introduces semantic colors: a way of specifying what a color's purpose is rather than its actual value. This allows the color to automatically adapt when dark mode is enabled.
In UIKit, these colors can be easily accessed via static members on UIColor
(e.g. UIColor.label()
, UIColor.secondaryLabel()
, etc.). An extensive list of all the available semantic colors can be found on this documentation page.
However, SwiftUI's Color
type does not have the equivalent static members. Therefore, this would be invalid:
// Error: Type 'Color?' has no member 'secondaryLabel'
var body: some View {
Text("Hello World!")
.color(.secondaryLabel)
}
How would I go about accessing these semantic colors in SwiftUI?
SwiftUI provides with multiple ways to initialize colors. One way to do it is using Color(red: ..., green: ..., blue: ...) . You can provide the RGB (Red, Green, blue) value on a 0-1 range. You can also initialize color with UIColor (from UIKit) and NSColor (from AppKit).
TLDR: Take your color and find it on Color Hex. Scroll down to find the RGB Percentages of your color and use that in the SwiftUI. Color struct to create the color in your code. In the below example the color #60364f becomes Color(red: 0.4192, green: 0.2358, blue: 0.3450) .
To use the color picker in Xcode, you can access it in two ways: Go to the Xcode's toolbar and click Edit -> Format -> Show Colors. After showing the picker, you can click Hide Colors to dismiss it.
The Color struct in SwiftUI has a UIColor initialiser. So for example you could change the Text foregroundColor using the label UIColor.
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
Text("Hello World")
.foregroundColor(Color(.label))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
ContentView()
ContentView()
.environment(\.colorScheme, .dark)
}
}
}
While Color
does not have static members for these semantic colors, according to the documentation, Color
does have an initializer which allows you to specify an AppearanceColorName
.
However, I say "according to the documentation" because, as of now, this initializer appears to be unavailable in Xcode. In a subsequent beta release, when this initializer becomes available, it can be used like this:
var body: some View {
Text("Hello World!")
.color(Color(apperanceName: .secondaryLabel))
}
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