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 ???")
        }
    }
}

结果:

"Hello world!" above "Height of first text is ???"

我现在想用“Hello World!”的高度替换 ???。我该怎么做?

解决方法

您可以:

  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)") 
        }
    }
}

结果:

"Hello world!" above "Height of first text is 20.333333"