如何检测图表标记上的点击手势?

时间:2018-08-19 20:55:49

标签: ios ios-charts

我正在使用Charts在应用程序中创建自定义图形。我遇到的一件事是检测图表标记上针对当前值显示的触摸事件。我想根据被点击的标记执行操作。该动作应输入由点击标记表示的数据条目。

我已阅读Selectable marker view & images at Y axis,但仍无法提出可行的解决方案。

如果有人可以提供代码示例,或者提供比上面链接中更详细的解释,以指示我正确的方向,那将是很好的。

谢谢

2 个答案:

答案 0 :(得分:1)

根据您的要求,Charts库的委托中已经具有该方法。

请检查以下代码:

  1. 将委托分配到您的ChartView,如下所示
lineChartView.delegate = self
  1. 类中的实现委托方法
public func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {

}

在这里,您可以在用户单击图表时编写代码。

希望此信息会有所帮助!

答案 1 :(得分:0)

我最终解决了这一问题,方法是将自己选择的ChartView子类化,并用我自己的覆盖了现有的轻敲手势识别器。

示例

final class CustomChartView: BarChartView {
    ...
    private func initialize() {
        ...
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapRecognized))
        self.addGestureRecognizer(tap)
    }

    @objc func tapRecognized(_ recognizer: UITapGestureRecognizer) {
        guard data !== nil else { return }

        switch recognizer.state {
            case .ended:
            // Detect whether or not the touch was inside a marker that was being presented
            // Otherwise, add/remove highlight as necessary

            if let marker = self.marker as? BalloonMarker {
                let location = recognizer.location(in: self)

                if !highlighted.isEmpty && marker.rect.contains(location) {
                    // In my case, I created custom property 'vertex' on BalloonMarker for easy reference to get `xValue`
                    let xValue = self.getTransformer(forAxis: .left).valueForTouchPoint(marker.vertex).x

                    // Do what you need to here with tap (call function, create custom delegate and trigger it, etc)
                    // In my case, my chart has a marker tap delegate
                    // ex, something like: `markerTapDelegate?.tappedMarker()`

                    return
                }
            }

            // Default tap handling
            guard isHighLightPerTapEnabled else { return }

            let h = getHighlightByTouchPoint(recognizer.location(in: self))

            if h === nil || h == self.lastHighlighted {
                lastHighlighted = nil
                highlightValue(nil, callDelegate: true)

            } else {
                lastHighlighted = h
                highlightValue(h, callDelegate: true)
            }

        default:
            break
    }
}