Last active
October 30, 2020 10:49
-
-
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)
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
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]) } | |
} | |
) | |
} | |
} |
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
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