Skip to content

Instantly share code, notes, and snippets.

@juliensagot
Created November 8, 2024 10:40
Show Gist options
  • Select an option

  • Save juliensagot/bc28d0b2f7c98c06d37cc1acf672e387 to your computer and use it in GitHub Desktop.

Select an option

Save juliensagot/bc28d0b2f7c98c06d37cc1acf672e387 to your computer and use it in GitHub Desktop.

Revisions

  1. juliensagot created this gist Nov 8, 2024.
    55 changes: 55 additions & 0 deletions ConditionalEnvironmentOverlay.swift
    Original 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