Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS charts - draw value only when highlighted

I want to highlight and show value only when tapping on the iOS-Chart. I enabled the highlight but not the values because I only want them when tap and highlight

lineChartDataSet.drawValuesEnabled = false
lineChartDataSet.highlightEnabled = true

Do I need this function?

func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {}
like image 548
Maruta Avatar asked Sep 24 '17 13:09

Maruta


1 Answers

It's an old question, but I think it's still actual for some developers.

If you want to show values, baloon or highlight bar only while user is touching a chart view you may catch a touch event with UILongPressGestureRecognizer.

I instantiated new TappableLineChartView class from LineChartView. But you can work with BarChartView in the same way. Also if you don't want to instantiate new classes, you can incorporate addTapRecognizer and chartTapped functions in your view controller.

In my example, I show and hide values, but in the same manner, you can show and hide a balloon or another marker.

class TappableLineChartView: LineChartView {

    public override init(frame: CGRect)
    {
        super.init(frame: frame)
        addTapRecognizer()
    }

    public required init?(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)
        addTapRecognizer()
    }

    func addTapRecognizer() {
        let tapRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(chartTapped))
        tapRecognizer.minimumPressDuration = 0.1
        self.addGestureRecognizer(tapRecognizer)
    }

    @objc func chartTapped(_ sender: UITapGestureRecognizer) {
        if sender.state == .began || sender.state == .changed {
            // show
            let position = sender.location(in: self)
            let highlight = self.getHighlightByTouchPoint(position)
            let dataSet = self.getDataSetByTouchPoint(point: position)
            dataSet?.drawValuesEnabled = true
            highlightValue(highlight)
        } else {
            // hide
            data?.dataSets.forEach{ $0.drawValuesEnabled = false }
            highlightValue(nil)
        }
    }
}
like image 50
AlexSmet Avatar answered Oct 18 '22 13:10

AlexSmet