Created
June 27, 2022 15:32
-
-
Save aheze/2560bfc413e98d77a3568a61bf80bde4 to your computer and use it in GitHub Desktop.
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
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() } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome. Thanks for sharing.