Skip to content

Instantly share code, notes, and snippets.

@GeorgeElsham
Last active March 3, 2023 16:02
Show Gist options
  • Save GeorgeElsham/661702161b5ed6f669d18e7463dc1385 to your computer and use it in GitHub Desktop.
Save GeorgeElsham/661702161b5ed6f669d18e7463dc1385 to your computer and use it in GitHub Desktop.
This is an example of using PreferenceKey with GeometryReader. Whenever this scaled red square changes geometry because of the space given by the parent view, the preference will update, updating the State variable. This will not causes State changes during view update issues.
struct ContentView: View {
@State private var size: CGFloat = 0
var body: some View {
Color.red
.scaledToFit()
.background(
GeometryReader { geo in
Color.clear.preference(
key: SizePreferenceKey.self,
value: geo.size.width
)
}
.onPreferenceChange(SizePreferenceKey.self) { newSize in
print(newSize)
size = newSize
}
)
}
}
struct SizePreferenceKey: PreferenceKey {
static let defaultValue: CGFloat = 0
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = nextValue()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment