我们如何从Swift Chart Legend中排除给定系列? 我很好奇,是否有一种方法可以从Swift图表提供的自动生成的传说中排除某些系列? 在此示例中,我将如何隐藏“系列1”,从le ...

问题描述 投票:0回答:1

FWIW,我已经知道我可以通过使用

.foregroundStyle(_:)Chart with all Series in Legend而不是

.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
swift swiftui swiftui-charts
1个回答
0
投票

.foregroundStyle(_:)

,我们将
.foregroundStyle(by:)

而不是应用于有关系列的数据。请注意,由于我对我来说看起来像是一个迅速的图表,因此仅当相关系列在另一个系列之前,这才能起作用。尝试将条件更改为
if series.name == "Series 2" {或任何其他系列,以查看不良行为。
LegendMinusASeriesSolB
,我们完全覆盖了传说的产生,因此我们可以轻松省略所讨论的系列。 结果是结果的样子:

    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.