使用Apple Swift Charts时如何创建保留配色且隐藏图例的图表
Swift Charts 保留多色效果同时隐藏图例实现方法
问题场景
使用 Swift Charts 框架时,通过 .foregroundStyle(by: .value("Shape", shape.type)) 修饰符可以自动为不同类别的柱状条分配区分度高的配色,但该修饰符会默认自动生成配套图例;如果直接删除该修饰符,多色效果会和图例一同消失。
默认带图例效果:
删除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)) } } } }
实现方案
在 Chart 控件上添加 .chartLegend(.hidden) 修饰符即可。该修饰符只会屏蔽图例的渲染,不会影响 .foregroundStyle(by:) 自动生成的多色配色逻辑。
修改后的BarChart代码:
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) } }
扩展:如果不需要完全隐藏图例,只是想调整图例位置,可以给
.chartLegend()传入对应位置参数,比如.chartLegend(.bottom)即可将图例放在图表底部。
内容的提问来源于stack exchange,提问作者Marcy
相关产品推荐
相关产品推荐

