Nik Payne
Nik Payne

Reputation: 151

How do you programmatically lighten or darken a dynamic Color in SwiftUI?

Others have covered how to lighten and darken UIColors in Swift, but I have not seen a good way to programmatically "lighten" and "darken" dynamic SwiftUI Colors.

I have green Text using Color(.systemGreen) that I would like to appear darker on light backgrounds and lighter on dark backgrounds.

Upvotes: 4

Views: 1954

Answers (1)

Cesare
Cesare

Reputation: 930

You need to observe which color theme is set now and use specific color depends on it. If you want use non-system color, it's better add new Color Set in Assets for light and dark modes.

import SwiftUI
struct temp_color: View {
    var colorScheme: ColorScheme
    var body: some View {
        Text("Hello, World!")
            .foregroundColor(colorScheme == .light ? Color(.systemGreen) : Color(.systemRed))}
}
struct temp_color_Previews: PreviewProvider {
static var previews: some View {
    temp_color(colorScheme: .light)
    }
}

Upvotes: 1

Related Questions