Created
October 30, 2020 20:33
-
-
Save dfrobison/fe75e03dacf4e2a1440d5051824622e1 to your computer and use it in GitHub Desktop.
[Get the size of a child view ]
This file contains 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 ChildSizeReader<Content: View>: View { | |
@Binding var size: CGSize | |
let content: () -> Content | |
var body: some View { | |
ZStack { | |
content() | |
.background( | |
GeometryReader { proxy in | |
Color.clear | |
.preference(key: SizePreferenceKey.self, value: proxy.size) | |
} | |
) | |
} | |
.onPreferenceChange(SizePreferenceKey.self) { preferences in | |
self.size = preferences | |
} | |
} | |
} | |
struct SizePreferenceKey: PreferenceKey { | |
typealias Value = CGSize | |
static var defaultValue: Value = .zero | |
static func reduce(value _: inout Value, nextValue: () -> Value) { | |
_ = nextValue() | |
} | |
} | |
// | |
// Usage | |
// | |
struct ChildSizeReaderExample: View { | |
@State var textSize: CGSize = .zero | |
var body: some View { | |
VStack { | |
ChildSizeReader(size: $textSize) { | |
Text("Hello I am some arbitrary text.") | |
} | |
Text("My size is \(textSize.debugDescription)!") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment