【问题标题】:How do I make all views the same height in a SwiftUI View with an HStack?如何在带有 HStack 的 SwiftUI 视图中使所有视图的高度相同?
【发布时间】: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 并得到了一个非常漂亮的简单图表:

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    这是可能的(似乎最简单的)方法。使用 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()
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 2021-12-21
      • 1970-01-01
      • 2021-05-26
      相关资源
      最近更新 更多