Skip to content

Instantly share code, notes, and snippets.

@aheze
Last active August 1, 2023 21:09
Show Gist options
  • Save aheze/f20b382b64ba62ee5f2613022da43700 to your computer and use it in GitHub Desktop.
Save aheze/f20b382b64ba62ee5f2613022da43700 to your computer and use it in GitHub Desktop.
public extension View {
/**
Read a view's size. The closure is called whenever the size changes.
From https://stackoverflow.com/a/66822461/14351818
*/
func sizeReader(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
size(newValue)
}
}
.hidden()
)
}
}
public struct ContentSizeReaderPreferenceKey: PreferenceKey {
public static var defaultValue: CGSize { return CGSize() }
public static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() }
}
/// Usage:
Text("Hi!")
.sizeReader { size in
print("Size: \(size)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment