【发布时间】: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 可以是此处确切大小未知的任何视图,因此无法设置静态大小。即没有GeometryReader,Graph 只能占用 VStack 中所需的垂直空间量。
【问题讨论】:
-
您要制作条形图吗?根据数据值采用动态条形高度?
标签: swiftui vstack geometryreader