FWIW,我已经知道我可以通过使用
.foregroundStyle(_:)
而不是
.foregroundStyle(by:)
struct LegendMinusASeriesSolA: View {
var body: some View {
Chart {
ForEach(data) { series in
let plot = LinePlot(series.points, x: .value("x", \.x), y: .value("y", \.y))
if series.name == "Series 1" {
plot
.foregroundStyle(.blue)
} else {
plot
.foregroundStyle(by: .value("Series", series.name))
}
}
}
.chartForegroundStyleScale(mapping: foregroundStyleForSeries)
.padding()
}
}
struct LegendMinusASeriesSolB: View {
var body: some View {
Chart {
ForEach(data) { series in
let plot = LinePlot(series.points, x: .value("x", \.x), y: .value("y", \.y))
if series.name == "Series 1" {
plot
.foregroundStyle(.blue)
} else {
plot
.foregroundStyle(by: .value("Series", series.name))
}
}
}
.chartForegroundStyleScale(mapping: foregroundStyleForSeries)
.chartLegend {
HStack {
ForEach(data) { series in
if series.name != "Series 1" {
Image(systemName: "circle.fill")
.foregroundStyle(series.color)
Text(series.name)
.foregroundStyle(Color.secondary)
}
}
}
.font(.caption2)
}
.padding()
}
}
来实现这一目标(并且只有在另一个系列之前将其定义)。但是感觉这是利用Swift图表中的无证件和有些奇怪的行为,我想知道是否有更好的方法,更直接地得到了API的支持。
它已经超过一个星期了,看来对此没有一个很好的答案。因此,除非有人建议一个更好的解决方案,否则我将为遇到这个问题的其他人分享我的两个解决方法。
LegendMinusASeriesSolA
.foregroundStyle(_:)
.foregroundStyle(by:)
而不是应用于有关系列的数据。请注意,由于我对我来说看起来像是一个迅速的图表,因此仅当相关系列在另一个系列之前,这才能起作用。尝试将条件更改为
if series.name == "Series 2" {
或任何其他系列,以查看不良行为。
在
LegendMinusASeriesSolB
,我们完全覆盖了传说的产生,因此我们可以轻松省略所讨论的系列。
结果是结果的样子: