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?
So I finally got this to work and wanted to add it to the community. Here is what my chart looks like:
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:
In the file you are implementing the graph, be sure to include ChartViewDelegate
Then implement the chartValueSelected method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With