Jacob
Jacob

Reputation: 422

SwiftUI - Accessing iOS 13's semantic colors

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?

Upvotes: 11

Views: 4138

Answers (2)

Edward
Edward

Reputation: 2974

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

Upvotes: 14

Jacob
Jacob

Reputation: 422

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

}

Upvotes: 4

Related Questions