[英]SwiftUI how to prevent from multiple BarMarks collapsing into 1 BarMark
Here's what my code looks like, and it shows 5 BarMarks.这是我的代码的样子,它显示了 5 个 BarMarks。
struct Record: Identifiable {
var id = UUID()
var altitude: Int
var speed: Double
var time: Int
}
struct TestView: View {
@State private var records:[Record] = [
Record(altitude: 15000, speed: 830, time: 1),
Record(altitude: 15000, speed: 830, time: 2),
Record(altitude: 15000, speed: 830, time: 3),
Record(altitude: 15000, speed: 830, time: 4),
Record(altitude: 15000, speed: 830, time: 5)
]
var body: some View {
VStack{
Chart(records) { record in
BarMark(x: .value("Date", String(record.time)), y: .value("Level", record.speed))
}.frame(height: 200)
}
}
}
But I want to show x-labels for only first one and last one.但我只想显示第一个和最后一个的 x 标签。
So here is what I have tried.所以这就是我尝试过的。 Provide empty X label strings when index is not first or last one using ternary operator.
当索引不是使用三元运算符的第一个或最后一个时,提供空 X label 字符串。
Now it shows X-labels only for first and last one, but now all three middle BarMarks got collpased in one.现在它只显示第一个和最后一个的 X 标签,但现在所有三个中间的 BarMarks 都合并为一个。
struct TestView: View {
@State private var records:[Record] = [
Record(altitude: 15000, speed: 830, time: 1),
Record(altitude: 15000, speed: 830, time: 2),
Record(altitude: 15000, speed: 830, time: 3),
Record(altitude: 15000, speed: 830, time: 4),
Record(altitude: 15000, speed: 830, time: 5)
]
var body: some View {
VStack{
Chart(0..<records.count, id: \.self) { index in
BarMark(x: .value("time", index == 0 || index == records.count-1 ? String(records[index].time) : ""), y: .value("speed", records[index].speed))
}.frame(height: 200)
}
}
}
Does anyone know why this behavior is happening and how I can prevent this from happening?有谁知道为什么会发生这种行为以及如何防止这种情况发生?
In your approach you are directly modifying the plot values.在您的方法中,您直接修改 plot 值。 So Chart "sees" only 3 different x values: "1","","5" – and adds up all y values with the x value "".
因此图表“看到”只有 3 个不同的 x 值:“1”、“”、“5”——并将所有 y 值与 x 值“”相加。
To achieve what you want you can directly modify the xAxis appearance:要实现您想要的效果,您可以直接修改 xAxis 外观:
Add this modifier to your chart and leave the plot values as in your initial code.将此修饰符添加到图表中,并保留初始代码中的 plot 值。
.chartXAxis {
AxisMarks { value in
AxisGridLine()
AxisTick()
// only show first and last xAxis value label
if value.index == 0 || value.index == value.count-1 {
AxisValueLabel()
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.