Skip to content

Instantly share code, notes, and snippets.

@aheze
Created June 27, 2022 15:32
Show Gist options
  • Save aheze/2560bfc413e98d77a3568a61bf80bde4 to your computer and use it in GitHub Desktop.
Save aheze/2560bfc413e98d77a3568a61bf80bde4 to your computer and use it in GitHub Desktop.
extension View {
/**
Read a view's size. The closure is called whenever the size itself changes, or the transaction changes (in the event of a screen rotation.)
From https://stackoverflow.com/a/66822461/14351818
*/
func readSize(size: @escaping (CGSize) -> Void) -> some View {
return background(
GeometryReader { geometry in
Color.clear
.preference(key: ContentSizeReaderPreferenceKey.self, value: geometry.size)
.onPreferenceChange(ContentSizeReaderPreferenceKey.self) { newValue in
DispatchQueue.main.async {
size(newValue)
}
}
}
.hidden()
)
}
}
struct ContentSizeReaderPreferenceKey: PreferenceKey {
static var defaultValue: CGSize { return CGSize() }
static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() }
}
@ivancantarino
Copy link

Awesome. Thanks for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment