问题描述
为了获得“Hello World!”文本的高度,我在其上附加了 .background()
的 GeometryReader
。现在,我只是使用 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 ???")
}
}
}
结果:
我现在想用“Hello World!”的高度替换 ???
。我该怎么做?
解决方法
您可以:
- 创建一个
@State
属性来存储高度 - 使用附加到
.onAppear {
的Color.clear
进行设置 - 用
???
替换\(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)")
}
}
}
结果: