Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a floating graph marker with ios-charts

I'm using the ios-charts framework and want to create a marker that floats over the graph when I touch and move my finger from side to side. I'm using a line chart just for reference.

However, I can't figure out how to get the position of the marker on the chart when I touch it.

I've read about subclassing MarkerView but that isn't working. Can you please show me how to get the position of the point that shows up when you touch an ios-chart?

like image 714
Rob Norback Avatar asked Sep 17 '15 04:09

Rob Norback


1 Answers

So I finally got this to work and wanted to add it to the community. Here is what my chart looks like:

enter image description here

When you run your finger over the chart the the reader above moves and reads the value from the chart.

To get this to work I had to do the following:

  1. In the file you are implementing the graph, be sure to include ChartViewDelegate

  2. Then implement the chartValueSelected method.

  3. If you then use the getMarkerPosition method, you'll be able to center your "marker" wherever you want.

Here's some sample code:

class MarkerView: UIView {
    @IBOutlet var valueLabel: UILabel!
    @IBOutlet var metricLabel: UILabel!
    @IBOutlet var dateLabel: UILabel!
}

let markerView = MarkerView()

func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight) { 

    let graphPoint = chartView.getMarkerPosition(entry: entry,  highlight: highlight)

    // Adding top marker
    markerView.valueLabel.text = "\(entry.value)"
    markerView.dateLabel.text = "\(months[entry.xIndex])"
    markerView.center = CGPointMake(graphPoint.x, markerView.center.y)
    markerView.hidden = false

}

markerView is a xib that I added manually to the main view that also contains the graph view. markerView is a UIView that contains three labels. It's the 3.0, impressions, and Apr you see in the picture.

graphPoint is the CGPoint located on the graph. You can use the x and y of the graphPoint to reposition your markerView. Here I simply kept the y value of the markerView the same and changed it's x-value to make it move back and forth on touch.

like image 127
Rob Norback Avatar answered Oct 02 '22 09:10

Rob Norback