我很好奇,有没有办法告诉chartXSelection(value:)
修饰符在响应用户手势时包含 x 轴区域?我知道在图表区域中开始点击并向下拖动是可行的,但我希望用户只需点击 x 轴上他们喜欢的值,然后通过 注册即可chartXSelection
。
请参阅下面的示例代码(经过编辑,包含高 axisMarks 来演示一个建议解决方案的问题):
private struct PlotPoint {
let x: Double
let y: Double
}
private struct PlotSeries: Identifiable {
let id: Int
let name: String
let points: [PlotPoint]
}
private let data: [PlotSeries] = [
PlotSeries(id: 0, name: "Series A", points: stride(from: 0.0, through: 1.0, by: 0.05).map { y in PlotPoint(x: y*y, y: y) }),
PlotSeries(id: 1, name: "Series B", points: stride(from: 0.0, through: 1.0, by: 0.05).map { y in PlotPoint(x: y*y, y: y/2) })
]
struct AxisTap: View {
@State private var selectedX: Double?
var body: some View {
VStack {
Chart {
if let selectedX {
BarMark(xStart: .value("x", selectedX), xEnd: .value("x", selectedX + 0.05))
.foregroundStyle(.yellow.opacity(0.5))
}
ForEach(data) { series in
let plot = LinePlot( series.points, x: .value("x", \.x), y: .value("y", \.y))
plot
.symbol(by: .value("Series", series.name))
.foregroundStyle(by: .value("Series", series.name))
}
}
.chartXAxis {
AxisMarks() { value in
AxisGridLine()
AxisTick()
AxisValueLabel() {
if let axisValue = value.as(Double.self) {
VStack {
Text("|")
Text("v")
Text("\(axisValue.formatted())")
}
}
}
}
}
.chartXSelection(value: $selectedX)
.padding()
Text("selectedX is: \(selectedX ?? 0.0)")
}
}
}
我希望用户能够点击 x 轴上的“0.5”并获得如下所示的结果(下面显示“selectedX 是:~0.5”)。
A
chartGesture
还会覆盖 x 轴所在的区域。现在您不再需要了
.chartXSelection(value: $selectedX)
,如果不需要以编程方式设置它,请考虑更改selectedX
为。@GestureState
对于更高的 x 轴,除了或 之外,您还可以在用于检测手势的矩形
Rectangle
下方添加。plotFrame
chartGesture
chartXSelection