Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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