SwiftUI - 如何从不同的视图中获取 GeometryReader size/height?

SwiftUI - How to get GeometryReader size/height from different View?

如何从另一个视图访问一个视图的大小?

为了获得“Hello world!”文本的高度,我附加了 GeometryReader.background()。现在,我只是使用 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!”的高度替换 ???。我该怎么做?

您可以:

  1. 制作一个@State属性来存储高度
  2. 使用附加到 Color.clear
  3. .onAppear { 进行设置
  4. ???替换为\(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)") 
        }
    }
}

结果: