ahe*_*eze 1 ios swift swiftui geometryreader
如何从另一个视图访问一个视图的大小?
为了获得“ 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 ???")
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
我现在想替换为“ 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)")
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果: