Reputation: 30318
How can I access the size of a View from another View?
To get the height of the "Hello world!" text, I attached a .background()
of GeometryReader
to it. For now, I'm just printing the height using let _ = print(proxy.size.height)
.
struct ContentView: View {
var body: some View {
VStack {
Text("Hello world!")
.background(
GeometryReader { proxy in
Color.clear /// placeholder
let _ = print(proxy.size.height) /// 20.333333333333332
}
)
Text("Height of first text is ???")
}
}
}
Result:
I now want to replace ???
with the height of the "Hello world!". How can I do this?
Upvotes: 1
Views: 6158
Reputation: 30318
You can:
@State
property to store the height.onAppear {
attached to Color.clear
???
with \(textHeight)
struct ContentView: View {
@State var textHeight = CGFloat(0) /// 1.
var body: some View {
VStack {
Text("Hello world!")
.background(
GeometryReader { proxy in
Color.clear
.onAppear { /// 2.
textHeight = proxy.size.height
}
}
)
/// 3.
Text("Height of first text is \(textHeight)")
}
}
}
Result:
Upvotes: 5