在 Swift Charts 中,签名为chartForegroundStyleScale
为每个数据系列设置 ShapeStyle 的方法是:
func chartForegroundStyleScale<DataValue, S>(_ mapping: KeyValuePairs<DataValue, S>) -> some View where DataValue : Plottable, S : ShapeStyle
The KeyValuePairs
初始化程序(init(dictionaryLiteral: (Key, Value)...)
)只接受一个可变参数,因此任何从数组初始化前景样式的尝试(在我的例子中<String, Color>
)导致错误:
Cannot pass array of type '[(String, Color)]' as variadic arguments of type '(String, Color)'
在我的应用程序中,图表系列的名称是根据数据动态设置的,因此尽管我可以生成[String : Color]
字典或数组(String, Color)
元组我看不出可以将其中任何一个传递到chartForegroundStyleScale
?除非我遗漏了一些东西,否则这似乎是 Swift 图表中的一个奇怪的限制,即系列名称需要为此修饰符进行硬编码?
您还可以将颜色数组传递给.chartForegroundStyleScale(range:)
。只要您按照添加图形标记的顺序将颜色添加到数组中,它就应该可以正常工作。
也不是非常优雅,但这种方法适用于任意数量或条目。
struct GraphItem: Identifiable {
var id = UUID()
var label: String
var value: Double
var color: Color
}
struct ContentView: View {
let data = [
GraphItem(label: "Apples", value: 2, color: .red),
GraphItem(label: "Pears", value: 3, color: .yellow),
GraphItem(label: "Melons", value: 5, color: .green)
]
var body: some View {
Chart {
ForEach(data, id: \.label) { item in
BarMark(
x: .value("Count", item.value),
y: .value("Fruit", item.label)
)
.foregroundStyle(by: .value("Fruit", item.label))
}
}
.chartForegroundStyleScale(range: graphColors(for: data))
}
func graphColors(for input: [GraphItem]) -> [Color] {
var returnColors = [Color]()
for item in input {
returnColors.append(item.color)
}
return returnColors
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)