[英]How to remove the value label above each bar in bar chart for ios-charts
[英]SwiftUI Charts: Adding Label To Bar Chart Bar
我在 SwiftUI 中使用 WWDC22 中為 iOS 16 引入的新圖表框架。
我希望每個條的值都顯示在條內,但無論如何我在 Charts 框架中都看不到這樣做。 我能做的最好的事情是使用 ZStack 並嘗試在圖表頂部分層文本,這可行,但隨着數據的變化,文本不會保持在欄中的中心。
有人在 SwiftUI 圖表中發現了一種本地執行此操作的方法嗎?
可以使用以下代碼使用覆蓋 position 和中心 alignment 來注釋條:
.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)
]
}
和數據 Model:
struct ShapeModel: Identifiable {
var type: String
var count: Double
var id = UUID()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.