Mar*_*rcy 2 swiftui swiftui-charts
Apple 的 Swift Charts 最近在 WWDC 上推出。然而,我的练习图有冗余。不需要图例。如何创建具有所有颜色但没有图例的图表?
\n\n使用 \xe2\x80\x9c.foregroundStyle(by: .value("Shape", shape.type))\xe2\x80\x9d 会导致图表自动向条形图添加多种颜色。但foregroundStyle也带有传奇色彩。删除 foregroundStyle 会同时删除图例和颜色:
\n\n这是最小的可重现代码:
\nimport Charts\nimport SwiftUI\n\nstruct ContentView: View {\n var body: some View {\n VStack {\n Text("Swift Chart Example")\n BarChart()\n .frame(width: 350, height: 350, alignment: .center)\n }\n }\n}\n\nstruct Shape: Identifiable {\n var type: String\n var count: Double\n var id = UUID()\n}\n\nlet data: [Shape] = [\n .init(type: "Square", count: 12),\n .init(type: "Heart", count: 10),\n .init(type: "Rectangle", count: 21),\n .init(type: "Star", count: 15),\n .init(type: "Circle", count: 8),\n .init(type: "Triangle", count: 6),\n]\n\nstruct BarChart: View {\n var body: some View {\n Chart {\n ForEach (data) { shape in\n BarMark (\n x: .value("Shape", shape.type),\n y: .value("Count", shape.count)\n )\n .foregroundStyle(by: .value("Shape", shape.type))\n }\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n
要删除图例,请将这行代码添加到图表中:
.chartLegend(.hidden)
Run Code Online (Sandbox Code Playgroud)
像这样:
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))
}
}
.chartLegend(.hidden)
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
此外,这些可以类似地用于从 X 轴和 Y 轴删除标签:
.chartXAxis(.hidden)
.chartYAxis(.hidden)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2177 次 |
| 最近记录: |