Search code examples
iosswiftswiftuiios-charts

SwiftUI iOS CHARTS: How to get highlighted value


Using iOS Charts (by Daniel Gindi https://github.com/danielgindi/Charts) and SwiftUI, I would like to get the selected value from a Line Chart, the highlighted value when the user tap it. The highlight is working, I can see the additional lines for this value.

After some research, I found we have to create this function: chartValueSelected() but it's never called in this case. I suppose I have to deal with the delegate but I did not find any solution or example with SwiftUI. Can someone help ? Thanks LineChart

    import Foundation
    import Charts
    import SwiftUI

    struct GraphMeterLine : UIViewRepresentable {
    var xArray:[Float] = [0,1,2,3,4]
    var yArray:[Float] = [0,3,6,2,12]
    var data = LineChartData()
    let chartline = LineChartView()

        func makeUIView(context: Context) -> LineChartView {
            return chartline
        }

        func updateUIView(_ uiView: LineChartView, context: Context) {
            //when data changes chartd.data update is required
            uiView.data = createGraph()
        }
    
    
    func createGraph() -> LineChartData {
        var lineChartEntry = [ChartDataEntry]()
       
            for i in 0..<yArray.count {
                let value = ChartDataEntry(x: Double(xArray[i]), y: Double(yArray[i]))
                lineChartEntry.append(value)
            }
            
        let line1 = LineChartDataSet(entries: lineChartEntry, label: "Number")
        

        data.addDataSet(line1)

                data.setDrawValues(false)
                return data
    }

    public func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
        print("To Display Values X/Y Values here")
    }
    
        typealias UIViewType = LineChartView
        
    }

Solution

  • Will try another one idea. I can't test it right now, so don't sure it will work, but it builds successfully, try it on your side. There is code I added in your code:

    var xArray:[Float] = [0,1,2,3,4]
    var yArray:[Float] = [0,3,6,2,12]
    var data = LineChartData()
    let chartline = LineChartView()
    
    class ChartDelegete: ChartViewDelegate {
        func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
            print("To Display Values X/Y Values here")
        }
    }
    
    let chartDelegete = ChartDelegete()
    
    func makeUIView(context: Context) -> LineChartView {
        chartline.delegate = chartDelegete
        return chartline
    }
    

    UPDATED after comment

    Old answer

    Add delegate to definition

    struct GraphMeterLine : UIViewRepresentable, ChartViewDelegate {
    

    and set delegate

    chartline.delegate = self 
    

    in makeUIView(context: call for example. It should work.