Skip to content

Instantly share code, notes, and snippets.

@StewartLynch
Last active May 19, 2023 23:22
Show Gist options
  • Save StewartLynch/6343adcabc99f3798f79377843f36cf3 to your computer and use it in GitHub Desktop.
Save StewartLynch/6343adcabc99f3798f79377843f36cf3 to your computer and use it in GitHub Desktop.
// Sample Use
struct ContentView: View {
@State private var size: CGSize = .zero
var body: some View {
VStack {
Text("\(size.width)")
Text("Hello World")
.getCGSize($size)
}
.padding()
}
}
// PreferenceKey
struct CGSizeKey: PreferenceKey {
static var defaultValue = CGSize.zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {
value = nextValue()
}
}
extension View {
func getCGSize(_ viewSize: Binding<CGSize>) -> some View {
background(
GeometryReader { proxy in
Color.clear
.preference(key: CGSizeKey.self, value: proxy.size)
}
.onPreferenceChange(CGSizeKey.self) { value in
viewSize.wrappedValue = value
}
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment