如何使用 HStack 使 SwiftUI 视图中的所有视图具有相同的高度?

Moz*_*ler 2 swift swiftui

我想要一个简单的图表,其中每个数据点都有一个可变高度的彩色矩形。彩色矩形下方的空白区域应扩大,以便底部数字对齐,就像顶部一行数字一样。

这是我的观点:

在此输入图像描述

因此,我想要一个惯用的解决方案,使底行数字与 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()
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑以显示最终结果:

我做了 Asperi 建议的更改,更改了.top对齐方式.bottom并得到了一个非常漂亮的简单图表:

在此输入图像描述

Asp*_*eri 5

这是可能的(似乎最简单的)方法。使用 Xcode 12 / iOS 14 进行测试

演示

struct DemoView: View {
    var dataSource = [1, 0, 34, 12, 59, 44]

    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)")
                    Color.clear
                        .frame(width: 20, height: CGFloat(dataSource.max() ?? 0))
                        .overlay(
                            Color.orange
                                .frame(height: CGFloat(self.dataSource[index]))
                        , alignment: .top)
                    Text("\(dataSource[index])")
                }
            }
            Spacer()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)