首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SwiftUI图表:向条形图栏添加标签

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

Stack Overflow用户
提问于 2022-07-29 16:18:59
回答 1查看 695关注 0票数 1

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

我希望每个条形图的值都显示在条形图中,但我在图表框架中并没有看到这样的效果。我所能做的最好是使用一个ZStack,并在图表上尝试分层文本,这样可以工作,但当数据发生变化时,不会将文本保持在条形图的中心位置。

有人在SwiftUI图表中发现了一种本土化的方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-30 21:15:13

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

代码语言:javascript
复制
.annotation(position: .overlay, alignment: .center) { 
  // your Text or other overlay here
}

带有注释的示例图表。

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

海图代码:

代码语言:javascript
复制
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)
                }
            }
        }
    }
}

样本数据:

代码语言:javascript
复制
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)
    ]
}

和数据模型:

代码语言:javascript
复制
struct ShapeModel: Identifiable {
    var type: String
    var count: Double
    var id = UUID()
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73168258

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档