【问题标题】:SwiftUI - How to get GeometryReader size/height from different View?SwiftUI - 如何从不同的视图中获取 GeometryReader 的大小/高度?
【发布时间】:2021-04-25 19:34:58
【问题描述】:

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

为了获得“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!”的高度替换???。我该怎么做?

【问题讨论】:

标签: ios swift swiftui geometryreader


【解决方案1】:

你可以:

  1. 创建一个@State 属性来存储高度
  2. 使用附加到Color.clear.onAppear { 设置它
  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)") 
        }
    }
}

结果:

【讨论】:

  • onAppear 仅在它出现时被调用,因此它不处理方向变化。
  • 我在 WWDC21 期间与一位 Apple 工程师交谈,他们说要处理方向,请附上 .onChange
猜你喜欢
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多