Created
June 19, 2021 10:50
-
-
Save novinfard/ceadf9824fef7958c6b8b22f00d6346e to your computer and use it in GitHub Desktop.
[Custom Environment variable in SwiftUI]
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
// 1. Create the key with a default value | |
private struct CaptionColorKey: EnvironmentKey { | |
static let defaultValue = Color(.secondarySystemBackground) | |
} | |
// 2. Extend the environment with our property | |
extension EnvironmentValues { | |
var captionBackgroundColor: Color { | |
get { self[CaptionColorKey.self] } | |
set { self[CaptionColorKey.self] = newValue } | |
} | |
} | |
// 3. Optional convenience view modifier | |
extension View { | |
func captionBackgroundColor(_ color: Color) -> some View { | |
environment(\.captionBackgroundColor, color) | |
} | |
} | |
// https://useyourloaf.com/blog/swiftui-custom-environment-values/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment