11

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?

Jacob
  • 402
  • 3
  • 14

2 Answers2

14

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)
        }
    }
}
Edward
  • 2,864
  • 2
  • 29
  • 39
4

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

}
Jacob
  • 402
  • 3
  • 14
  • 1
    Actually, the reason this appears unavailable in Xcode is because this API is macOS only. It says so in the documentation. If you create a macOS project and use SwiftUI, this should be available. – l_priebe Jun 16 '19 at 15:04
  • apperanceName is not used anymore – Medhi Apr 25 '22 at 15:46