我认为你必须用
chartOverlay
.chartXAxis(.hidden)
.chartOverlay { proxy in
if let y = proxy.position(forY: 0.0) {
ForEach(items) { item in
if let x = proxy.position(forX: item.month) {
Text("\(item.month)")
.font(.system(size: 12, weight: .bold))
.padding(.horizontal, 12)
.padding(.vertical, 8)
.background(Color.red.opacity(0.3))
.cornerRadius(4)
.position(x: x, y: y + 40) // +40 to offset the label downwards a bit
.onTapGesture {
print("Tapped on label \(item.month)")
}
}
}
}
}
为了防止标签被绘图区域剪切,您还应该添加一些底部填充:
.chartPlotStyle { plot in
plot.padding(.bottom, 30)
}
至于检测酒吧的水龙头,你可以做:
.chartGesture{ proxy in
SpatialTapGesture().onEnded { value in
guard let x = proxy.value(atX: value.location.x, as: String.self),
let xRange = proxy.positionRange(forX: x) else { return }
let rangeWidth = xRange.upperBound - xRange.lowerBound
// assuming the bars occupy half of the available width
// i.e. BarMark(x: ..., y: ..., width: .ratio(0.5))
let barRatio = 0.5
let barRange = (xRange.lowerBound + rangeWidth * barRatio / 2)...(xRange.upperBound - rangeWidth * barRatio / 2)
guard barRange.contains(value.location.x),
let item = items.first(where: { $0.month == x }),
let y = proxy.position(forY: item.revenue),
let maxY = proxy.position(forY: 0.0),
value.location.y >= y && value.location.y <= maxY else {
return
}
print("Tapped on bar \(x)")
}
}