macOS开发中Charts框架如何用鼠标悬浮替代点击获取chartValue
macOS 下 Charts 框架悬浮获取蜡烛图数值实现方案
实现逻辑
Charts 框架本身提供了视图坐标到图表数据的映射能力,只需要通过悬浮手势获取到鼠标在CombinedChartView内的坐标,再调用框架内置的坐标转换方法即可拿到对应位置的CandleChartDataEntry数据。
具体步骤
- 给图表组件添加悬浮手势识别器
原生macOS开发使用NSHoverGestureRecognizer,Mac Catalyst开发使用UIHoverGestureRecognizer即可:
// 原生macOS示例 let hoverGesture = NSHoverGestureRecognizer(target: self, action: #selector(handleHover(_:))) combinedChartView.addGestureRecognizer(hoverGesture)
- 实现手势回调,转换坐标获取对应数据
@objc func handleHover(_ gesture: NSHoverGestureRecognizer) { // 仅处理悬浮进入、移动状态 guard gesture.state == .began || gesture.state == .changed else { // 悬浮离开时取消高亮 if gesture.state == .ended || gesture.state == .exited { combinedChartView.highlightValue(nil) combinedChartView.delegate?.chartValueNothingSelected?(combinedChartView) } return } // 获取鼠标在图表视图内的坐标 let touchPoint = gesture.location(in: combinedChartView) // 校验坐标是否在图表有效绘制区域内,排除坐标轴、空白边距区域 guard combinedChartView.isInsideContent(pt: touchPoint) else { return } // 取蜡烛图数据集,索引要和你实际添加到CombinedData中的顺序对应 guard let candleDataSet = combinedChartView.combinedData?.candleData?.dataSets[0] as? CandleChartDataSet else { return } // 获取离触摸点最近的蜡烛数据条目索引 let entryIndex = candleDataSet.entryIndex(x: touchPoint.x, y: touchPoint.y, rounding: .closest) guard entryIndex >= 0, entryIndex < candleDataSet.entryCount else { return } guard let targetEntry = candleDataSet.entryForIndex(entryIndex) as? CandleChartDataEntry else { return } // 手动触发原点击选中的代理方法,和原有点击逻辑保持一致 let highlight = Highlight(x: targetEntry.x, y: targetEntry.y, dataSetIndex: 0) combinedChartView.highlightValue(highlight) combinedChartView.delegate?.chartValueSelected?(combinedChartView, entry: targetEntry, highlight: highlight) }
注意事项
- 上述代码中
dataSetIndex需要和你实际添加蜡烛图数据集到CombinedChartData的索引保持一致,避免拿错其他类型的数据集 - 如果不需要保持原有点击逻辑的效果,可以不用手动调用代理方法,直接使用拿到的
targetEntry处理业务逻辑即可
内容的提问来源于stack exchange,提问作者Serhii Didanov
相关产品推荐
相关产品推荐

