Skip to content

Instantly share code, notes, and snippets.

@juliensagot
Created November 8, 2024 10:40
Show Gist options
  • Save juliensagot/bc28d0b2f7c98c06d37cc1acf672e387 to your computer and use it in GitHub Desktop.
Save juliensagot/bc28d0b2f7c98c06d37cc1acf672e387 to your computer and use it in GitHub Desktop.
ConditionalEnvironmentOverlay
private struct ConditionalEnvironmentOverlay<Value: Equatable, OverlayContent: View>: ViewModifier {
@Environment(\.self) private var environmentValues
private let keyPath: KeyPath<EnvironmentValues, Value>
private let value: Value
private let overlayContent: OverlayContent
init(
condition: KeyPath<EnvironmentValues, Value>,
equals value: Value,
content: OverlayContent
) {
self.keyPath = condition
self.value = value
self.overlayContent = content
}
func body(content: Content) -> some View {
content
.overlay {
if environmentValues[keyPath: keyPath] == value {
overlayContent
}
}
}
}
extension View {
func overlay<T: Equatable>(
when: KeyPath<EnvironmentValues, T>,
equals: T,
@ViewBuilder content: () -> some View
) -> some View {
modifier(
ConditionalEnvironmentOverlay(
condition: when,
equals: equals,
content: content()
)
)
}
}
struct SampleView: View {
var body: some View {
Text("Hello World!")
// → Usage:
.overlay(when: \.colorScheme, equals: .dark) {
Color.red
}
}
}
// Beware of performances before iOS 17! (106310433)
// https://developer.apple.com/documentation/ios-ipados-release-notes/ios-ipados-17-release-notes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment