SwiftUI 图表:向条形图栏添加标签

问题描述 投票:0回答:1

我正在 SwiftUI 中使用 WWDC22 中针对 iOS 16 引入的新图表框架。

我希望每个条形的值显示在条形内部,但无论如何我在图表框架中都看不到这样做。我能做的最好的事情就是使用 ZStack 并尝试在图表顶部分层文本,这可行,但随着数据变化,文本不会保持在栏中居中。

有人发现了一种在 SwiftUI Charts 中本地执行此操作的方法吗?

ios swift swiftui charts swiftui-charts
1个回答
9
投票

可以使用以下代码使用覆盖位置和中心对齐来注释条形:

.annotation(position: .overlay, alignment: .center) { 
  // your Text or other overlay here
}

带有注释的示例图表。

下面提供了用于创建图表的完整代码以供参考。

图表代码:

struct BarChart4: View {
    var body: some View {
        VStack(alignment: .center)  {
            Text("Basic Bar Chart")
                .font(.callout)
                .foregroundStyle(.secondary)
            
            Chart (BarData4.data) { shape in
                BarMark (
                    x: .value("Shape", shape.type),
                    y: .value("Count", shape.count)
                )
                .annotation(position: .overlay, alignment: .center) {
                    Text("\(shape.count, format: .number.precision(.fractionLength(0)))")
                        .foregroundColor(.white)
                }
            }
        }
    }
}

样本数据:

struct BarData4 {
    static let data: [ShapeModel] = [
        .init(type: "Square",    count: 12),
        .init(type: "Heart",     count: 10),
        .init(type: "Rectangle", count: 21),
        .init(type: "Star",      count: 15),
        .init(type: "Circle",    count: 8),
        .init(type: "Triangle",  count: 6)
    ]
}

数据模型:

struct ShapeModel: Identifiable {
    var type: String
    var count: Double
    var id = UUID()
}
© www.soinside.com 2019 - 2024. All rights reserved.