Skip to content

Instantly share code, notes, and snippets.

@jasdev
Last active April 24, 2020 19:57
Show Gist options
  • Save jasdev/7695d8762d9aece1abbe843110b47297 to your computer and use it in GitHub Desktop.
Save jasdev/7695d8762d9aece1abbe843110b47297 to your computer and use it in GitHub Desktop.
objc.io’s geometryPreference modifier and Preference view for propagating up proxied geometries and reading them.
import SwiftUI
struct Preference<PreferenceKey: SwiftUI.PreferenceKey, Content: View>: View
where PreferenceKey.Value: Equatable {
private let content: (PreferenceKey.Value) -> Content
@State private var value: PreferenceKey.Value = PreferenceKey.defaultValue
init(
_ key: PreferenceKey.Type,
@ViewBuilder content: @escaping (PreferenceKey.Value) -> Content
) {
self.content = content
}
var body: some View {
content(value)
.onPreferenceChange(PreferenceKey.self) { self.value = $0 }
}
}
extension View {
func geometryPreference<PreferenceKey: SwiftUI.PreferenceKey>(
_ key: PreferenceKey.Type,
value: @escaping (GeometryProxy) -> PreferenceKey.Value
) {
overlay(
GeometryReader { proxy in
Color
.clear
.preference(key: key, value: value(proxy))
}
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment