Skip to content

Instantly share code, notes, and snippets.

@novinfard
Created June 19, 2021 10:50
Show Gist options
  • Save novinfard/ceadf9824fef7958c6b8b22f00d6346e to your computer and use it in GitHub Desktop.
Save novinfard/ceadf9824fef7958c6b8b22f00d6346e to your computer and use it in GitHub Desktop.
[Custom Environment variable in SwiftUI]
// 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