Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Accessing iOS 13's semantic colors

Tags:

swiftui

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?

like image 587
Jacob Avatar asked Jun 14 '19 00:06

Jacob


People also ask

How do I specify 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).

How do I use RGB in SwiftUI?

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

How do I use color picker in Xcode?

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.


2 Answers

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)
        }
    }
}
like image 168
Edward Avatar answered Sep 17 '22 01:09

Edward


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

}
like image 37
Jacob Avatar answered Sep 20 '22 01:09

Jacob