Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created March 9, 2020 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseidhof/7a861afa58d098be64586025020bd65f to your computer and use it in GitHub Desktop.
Save chriseidhof/7a861afa58d098be64586025020bd65f to your computer and use it in GitHub Desktop.
SwiftUI helpers
struct <#MyView#>: View {
var body: some View {
<#body#>
}
}
extension View {
func geometryPreference<P: PreferenceKey>(_ key: P.Type, value: @escaping (GeometryProxy) -> P.Value) -> some View {
overlay(GeometryReader { proxy in
Color.clear.preference(key: P.self, value: value(proxy))
})
}
}
struct Preference<P: PreferenceKey, Content: View>: View where P.Value: Equatable {
let content: (P.Value) -> Content
@State private var value: P.Value = P.defaultValue
init(_ key: P.Type, @ViewBuilder content: @escaping (P.Value) -> Content) {
self.content = content
}
var body: some View {
content(value)
.onPreferenceChange(P.self) { self.value = $0 }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment