【发布时间】:2022-06-16 04:40:08
【问题描述】:
Apple 的 Swift Charts 最近在 WWDC 上推出。但是,我的练习表有冗余。不需要图例。如何创建包含所有颜色但没有图例的图表?
使用“.foregroundStyle(by: .value("Shape", shape.type))”会导致图表自动为条形添加多种颜色。但是foregroundStyle 也带有图例。删除 foregroundStyle 会同时删除图例和颜色:
这是最小的可重现代码:
import Charts
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Text("Swift Chart Example")
BarChart()
.frame(width: 350, height: 350, alignment: .center)
}
}
}
struct Shape: Identifiable {
var type: String
var count: Double
var id = UUID()
}
let data: [Shape] = [
.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 BarChart: View {
var body: some View {
Chart {
ForEach (data) { shape in
BarMark (
x: .value("Shape", shape.type),
y: .value("Count", shape.count)
)
.foregroundStyle(by: .value("Shape", shape.type))
}
}
}
}
【问题讨论】: