SwiftUI - 如何从不同视图获取 GeometryReader 大小/高度?

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!??? ”的高度。我怎样才能做到这一点?

ahe*_*eze 5

你可以:

  1. 创建一个@State属性来存储高度
  2. .onAppear {使用附加的设置它Color.clear
  3. ???用。。。来代替\(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)

结果:

“你好世界!”  上面“第一个文本的高度是 20.333333”