Skip to content

Instantly share code, notes, and snippets.

@erdemildiz
Created June 1, 2022 13:42
Show Gist options
  • Save erdemildiz/58e4ec4c37cff5642ceee3b9fdefc8ca to your computer and use it in GitHub Desktop.
Save erdemildiz/58e4ec4c37cff5642ceee3b9fdefc8ca to your computer and use it in GitHub Desktop.
Custom Environment usage SwiftUI
// Source: https://useyourloaf.com/blog/swiftui-custom-environment-values/
// 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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment