4

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.

  • Using the .contrast() modifier increases the green's saturation but doesn't really make it darker.
  • Using the .brightness() modifier with a negative makes it darker for both light and dark mode, which doesn't really work for dark mode since it's harder to read.
Nik Payne
  • 151
  • 8

1 Answers1

1

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)
    }
}
Nizami
  • 728
  • 1
  • 6
  • 24