Skip to content

Instantly share code, notes, and snippets.

@zntfdr
Last active December 7, 2021 15:30
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zntfdr/f735039b13265d7b25099f524e2116d9 to your computer and use it in GitHub Desktop.
Save zntfdr/f735039b13265d7b25099f524e2116d9 to your computer and use it in GitHub Desktop.
// Original article here: https://fivestars.blog/swiftui/swiftui-share-layout-information.html
import SwiftUI
extension View {
func readSize(onChange: @escaping (CGSize) -> Void) -> some View {
background(
GeometryReader { geometryProxy in
Color.clear
.preference(key: SizePreferenceKey.self, value: geometryProxy.size)
}
)
.onPreferenceChange(SizePreferenceKey.self, perform: onChange)
}
}
private struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment