【发布时间】:2023-04-07 04:49:02
【问题描述】:
我想要一个简单的图表,每个数据点都有一个高度可变的彩色矩形。 彩色矩形下方的空白区域应扩大,以便底部数字对齐,就像顶部数字行一样。
这是我的看法:
所以我想要一个惯用的解决方案,让最后一行数字与 59 对齐。欢迎任何为我指明正确方向的建议。谢谢。
这是我目前所拥有的:
struct DemoView: View {
var dataSource = [1, 0, 34, 12, 59, 44]
/// Provide a Dynamic Height Based on the Tallest View in the Row
@State private var height: CGFloat = .zero // < calculable height
/// The main view is a row of variable height views
var body: some View {
HStack(alignment: .top) {
Spacer()
/// i want these to all be the same height
ForEach(0 ..< 6) { index in
VStack {
Text("\(index)")
Rectangle()
.fill(Color.orange)
.frame(width: 20, height: CGFloat(self.dataSource[index]))
Text("\(dataSource[index])")
}
}
Spacer()
}
.alignmentGuide(.top, computeValue: { d in
DispatchQueue.main.async {
self.height = max(d.height, self.height)
}
return d[.top]
})
}
}
struct Demo_Preview: PreviewProvider {
static var previews: some View {
DemoView()
}
}
编辑以显示最终结果:
我进行了 Asperi 建议的更改,将 .top 对齐更改为 .bottom 并得到了一个非常漂亮的简单图表:
【问题讨论】: