Skip to content

Instantly share code, notes, and snippets.

@Czajnikowski
Last active October 30, 2020 10:49
Show Gist options
  • Save Czajnikowski/27c038d6d7742369335b77c2e161c377 to your computer and use it in GitHub Desktop.
Save Czajnikowski/27c038d6d7742369335b77c2e161c377 to your computer and use it in GitHub Desktop.
My take on the propagation of anchor preferences. Inspired by @Pyroh (https://github.com/Dimillian/ACHNBrowserUI/commit/133d3a3b8cb72d163ea58e6e1fed017a8c97c536)
import SwiftUI
extension View {
func propagate<Key>(
_ transform: @escaping (CGRect) -> Key.Value,
of source: Anchor<CGRect>.Source = .bounds,
using key: Key.Type
) -> some View where Key: PreferenceKey {
_propagate(transform, of: source, using: key)
}
func propagate<Key>(
_ transform: @escaping (CGPoint) -> Key.Value,
of source: Anchor<CGPoint>.Source = .center,
using key: Key.Type
) -> some View where Key: PreferenceKey {
_propagate(transform, of: source, using: key)
}
private func _propagate<Key, AnchorValue>(
_ transform: @escaping (AnchorValue) -> Key.Value,
of source: Anchor<AnchorValue>.Source,
using key: Key.Type
) -> some View where Key: PreferenceKey {
overlay(
GeometryReader { proxy in
Color.clear
.anchorPreference(key: key, value: source) { transform(proxy[$0]) }
}
)
}
}
import SwiftUI
extension View {
func storeValue<Key>(
from key: Key.Type = Key.self,
in storage: Binding<Key.Value>
) -> some View where Key: PreferenceKey, Key.Value: Equatable {
onPreferenceChange(key, perform: { storage.wrappedValue = $0 })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment