【问题标题】:How to limit size of GeometryReader inside a VStack如何限制 VStack 内 GeometryReader 的大小
【发布时间】:2020-05-06 10:12:51
【问题描述】:

我想阻止 GeometryReader 干扰我在 VStack 中的布局,但我不确定正确的方法是什么。

以带有标题和说明的简单图表为例:

struct Graph: View {
  var body: some View {
    HStack(spacing: 0) {
      Color.red.frame(width: 100, height: 80)
      Color.blue.frame(width: 100, height: 120)
      Color.green.frame(width: 100, height: 180)
    }
  }
}

struct GraphExample: View {
  var body: some View {
    VStack {

      Text("My graph")

      // Graph represents a custom view with a natural and non-static height
      Graph()

      Text("My graph caption")
    }
  }
}

产生这个预期的结果:

但是,如果我们更新 Graph 视图以使用 GeometryReader 将图形均匀地分割到屏幕宽度上,则布局会发生变化。

struct Graph: View {
  var body: some View {
    GeometryReader { proxy in
      HStack(spacing: 0) {
        Color.red.frame(width: proxy.size.width / 3, height: 80)
        Color.blue.frame(width: proxy.size.width / 3, height: 120)
        Color.green.frame(width: proxy.size.width / 3, height: 180)
      }
    }
  }
}

这会使Graph 视图填满VStack 中的所有可用空间

有没有办法让Graph 视图仅填充其自然高度,并且在仍使用GeometryReader 时不消耗所有可用高度。

请记住,Graph 可以是此处确切大小未知的任何视图,因此无法设置静态大小。即没有GeometryReaderGraph 只能占用 VStack 中所需的垂直空间量。

【问题讨论】:

  • 您要制作条形图吗?根据数据值采用动态条形高度?

标签: swiftui vstack geometryreader


【解决方案1】:

这是可能的解决方案。使用 Xcode 11.4 / iOS 13.4 测试

struct Graph: View {
  @State private var width = UIScreen.main.bounds.width // just initial constant
  var body: some View {
      HStack(spacing: 0) {
        Color.red.frame(width: width / 3, height: 80)
        Color.blue.frame(width: width / 3, height: 120)
        Color.green.frame(width: width / 3, height: 180)
      }.background(GeometryReader { gp -> Color in
        let frame = gp.frame(in: .local)
        DispatchQueue.main.async {
            self.width = frame.size.width // << dynamic, on layout !!
        }
        return Color.clear
      })
  }
}

【讨论】:

  • 看起来很疯狂,可能会导致布局循环。尤其是DispatchQueue.main.async 部分。
猜你喜欢
  • 2020-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
相关资源
最近更新 更多