How to detect tap gesture on chart marker?

后端 未结 2 1951
故里飘歌
故里飘歌 2021-01-24 13:36

I am using Charts to create custom graphs in an application. The one thing I am having trouble with is detecting touch events on the chart marker that is presented for the curre

相关标签:
2条回答
  • 2021-01-24 13:58

    As per your requirement Charts library already have that method in its delegate.

    Please check below code :

    1. Assign delegate to your ChartView like below
    lineChartView.delegate = self
    
    1. Implement Delegate method in your class
    public func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
    
    }
    

    Here you can write your code while user click on chart.

    Hope this info will helps!

    0 讨论(0)
  • 2021-01-24 14:14

    I ended up solving this by subclassing the ChartView of my choice and overriding the existing tap gesture recognizer with my own.

    Example

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题