Last active
August 1, 2023 21:09
-
-
Save aheze/f20b382b64ba62ee5f2613022da43700 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
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