Created
November 8, 2024 10:40
-
-
Save juliensagot/bc28d0b2f7c98c06d37cc1acf672e387 to your computer and use it in GitHub Desktop.
Revisions
-
juliensagot created this gist
Nov 8, 2024 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,55 @@ 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