使用iOS图表进行交互式跟踪.如何

JGu*_*Guo 4 ios swift ios-charts

使用iOS图表(作者Daniel Gindi https://github.com/danielgindi/Charts),是否可以跟踪触摸?因此,当我在屏幕上移动手指而不是平移图形时,它会不断突出显示我触摸的条目.像下图这样的东西.

我想可能UIGestureRecognizer在图表视图中添加一个,获取触摸的位置,并以编程方式突出显示该条目.但是我怎样才能获得该特定位置的条目?谢谢

在此输入图像描述

JGu*_*Guo 7

我想出来为你节省一些时间

在此输入图像描述

extension GraphViewController: ChartViewDelegate {

    func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {

        // I used the x pixel property of the highlight to update the
        // position of the floating label, and set its text to the 
        // x value of the selected entry
        floatingLabelCenterConstraint?.constant = highlight.xPx
        floatingLabel.text = "  Mar 14  \(highlight.x)"

        // Create the nice transition animation
        // fadeIn() and fadeOut() are simple extension methods I wrote
        if floatingLabel.isHidden {
            floatingLabel.fadeIn()
            subscripts.fadeOut()
        }

        // This gives you the y value of the selected entry
        greenNumber.text = NSString(format: "%.2f", highlight.y) as String
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,只有在移动手指时才会调用此委托方法.您需要一种方法来判断平移手势何时结束.图表没有开箱即用的委托方法,因此您需要添加它.转到ChartViewBase.swift源文件,将以下内容添加到ChartViewDelegate协议中

public protocol ChartViewDelegate
{
    ...
    @objc optional func panGestureEnded(_ chartView: ChartViewBase)
}
Run Code Online (Sandbox Code Playgroud)

然后BarLineChartViewBase.swift去找panGestureRecognized功能

@objc private func panGestureRecognized(_ recognizer: NSUIPanGestureRecognizer)
{
    ...
    else if recognizer.state == NSUIGestureRecognizerState.ended || recognizer.state == NSUIGestureRecognizerState.cancelled
    {
    ...

    // Add this line at the end
    delegate?.panGestureEnded?(self)
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,返回到viewController并添加以下内容.现在一切都像魅力一样

func panGestureEnded(_ chartView: ChartViewBase) {
    subscripts.fadeIn()
    floatingLabel.fadeOut()

    // clear selection by setting highlightValue to nil
    chartView.highlightValue(nil)
}
Run Code Online (Sandbox Code Playgroud)