Created
June 1, 2022 13:42
-
-
Save erdemildiz/58e4ec4c37cff5642ceee3b9fdefc8ca to your computer and use it in GitHub Desktop.
Custom Environment usage 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
// 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