Created
June 18, 2023 09:34
-
-
Save DavidBemerguy/f1c1df7393d89017af70c531fdde52cc to your computer and use it in GitHub Desktop.
View modifier for dynamic color
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
var body: some View { | |
VStack { | |
Text("Hello, world!") | |
.dynamicColor((.blue, .red)) | |
} | |
.padding() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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