Skip to content

Instantly share code, notes, and snippets.

@DavidBemerguy
Created June 18, 2023 09:34
Show Gist options
  • Save DavidBemerguy/f1c1df7393d89017af70c531fdde52cc to your computer and use it in GitHub Desktop.
Save DavidBemerguy/f1c1df7393d89017af70c531fdde52cc to your computer and use it in GitHub Desktop.
View modifier for dynamic color
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, world!")
.dynamicColor((.blue, .red))
}
.padding()
}
}
import SwiftUI
typealias DynamicColor = (light: Color, dark: Color)
struct DynamicColorViewModifier: ViewModifier {
@Environment(\.colorScheme) var colorScheme
var dynamicColor: DynamicColor
func body(content: Content) -> some View {
content.foregroundColor(customColor)
}
private var customColor: Color {
if colorScheme == .dark {
return dynamicColor.dark
}
else {
return dynamicColor.light
}
}
}
extension View {
func dynamicColor(_ dynamicColor: DynamicColor) -> some View {
self.modifier(DynamicColorViewModifier(dynamicColor: dynamicColor))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment