如何在 SwiftUI 的 GeometryReader 中定义变量

How to define variables inside a GeometryReader in SwiftUI

我想根据视图的大小计算视图内形状的线宽。浏览 Whosebug 上的各种帖子,我认为解决方案是使用这样的 GeometryReader:

struct MyView: View {
    var body: some View {
        GeometryReader { geometry in
           // Here goes your view content,
           // and you can use the geometry variable
           // which contains geometry.size of the parent
           // You also have function to get the bounds
           // of the parent: geometry.frame(in: .global)
        }
    }
}

我的问题是,如何在 GeometryReader 结构中定义用于视图的变量?我试图在 "GeometryReader { geometry in" 行之后直接放置一个 var 语句,但这会导致编译器错误。

这似乎是一个与函数生成器相关的错误(从 Beta 3 开始),我建议就此提交反馈。

我一直在使用的解决方法是在单独的方法中使用 GeometryProxy 和显式 return.


var body: some View {
  GeometryReader { proxy in
    self.useProxy(proxy)
  }
}

func useProxy(_ proxy: GeometryProxy) -> some View {
  var width = proxy.size.width
  return VStack {
    // use width in here
  }
}