SwiftUI Chart拖动时Capsule无法贴合折线的定位问题求助
SwiftUI Chart 指示器贴合折线问题
我实现了一个SwiftUI Chart,想要根据用户拖动的位置获取折线对应点的Y值,从而让Capsule指示器精准定位在折线的正确位置。但目前代码只能显示用户在图表上的拖动位置,无法让指示器贴合折线。尝试使用value(atY:as:)方法也没能解决问题,附上代码及效果截图,恳请指点问题所在。
struct ContentView: View { @State private var numbers = (0...10).map { _ in Int.random(in: 0...10) } @State private var indicatorIndex = 0 @State private var indicatorNumber = 0.0 @State private var indicatorLocation = CGPointMake(0, 0) var body: some View { Chart { ForEach(Array(zip(numbers, numbers.indices)), id: \.0) { number, index in LineMark( x: .value("Index", index), y: .value("Value", number) ) } } .chartOverlay { proxy in GeometryReader { geometry in Capsule() .strokeBorder(Color.red, lineWidth: 1.0) .background(Color.blue) .frame(width: 80, height: 20) .overlay { HStack { Text("\(indicatorIndex)") .font(.system(size: 12.0)) .fontWeight(.semibold) .foregroundStyle(.red) Text("\(indicatorNumber)") .font(.system(size: 12.0)) .fontWeight(.semibold) .foregroundStyle(.white) } } .offset(x: indicatorLocation.x, y: indicatorLocation.y) Rectangle().fill(.clear).contentShape(Rectangle()) .gesture( DragGesture() .onChanged { value in // Convert the gesture location to the coordinate space of the plot area. let origin = geometry[proxy.plotAreaFrame].origin let location = CGPoint( x: value.location.x - origin.x, y: value.location.y - origin.y ) // Get the x (date) and y (price) value from the location. let (index, number) = proxy.value(at: location, as: (Int, Double).self) ?? (0, 0) let test = proxy.value(atY: origin.x, as: Double.self) indicatorIndex = index indicatorNumber = number indicatorLocation = CGPoint(x: value.location.x, y: test ?? 0.0) print("Location: \(number) - number, \(index) - index , \(test) test") } ) } } } }
效果截图
- 当前效果:

- 期望效果:

内容的提问来源于stack exchange,提问作者peter flanagan
相关产品推荐
相关产品推荐

