Last active
March 3, 2023 16:02
-
-
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.
This file contains hidden or 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
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