Last active
April 24, 2020 19:57
-
-
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.
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 | |
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