Mehdi
Mehdi

Reputation: 1362

How to implement Charts in SwiftUI?

How can I make a chart view using Charts library in SwiftUI

In other words, how to make a UIViewRepresentable for it?

Upvotes: 6

Views: 6655

Answers (2)

Leigh Yeh
Leigh Yeh

Reputation: 1

If you want to update the view of the graph every time the data changes, add a UpdateData() function where you set and return your LineChartData() object.

Then set uiView.data = UpdateData() and call uiView.notifyDataSetChanged().
This should re-render your graph.

Upvotes: 0

SpringN
SpringN

Reputation: 954

Here is some sample code that should get you started. Not sure if this is best practice, but it was the easiest way to get me going with Charts and SwiftUI. Hope this helps!

import SwiftUI
import Charts

struct GraphSwiftUI: View {
    var body: some View {
        GeometryReader { p in
            VStack {
                LineChartSwiftUI()
                    //use frame to change the graph size within your SwiftUI view
                    .frame(width: p.size.width, height: p.size.height/5, alignment: .center)
            }
        }
    }
}

struct LineChartSwiftUI: UIViewRepresentable {
    let lineChart = LineChartView()

    func makeUIView(context: UIViewRepresentableContext<LineChartSwiftUI>) -> LineChartView {
        setUpChart()
        return lineChart
    }

    func updateUIView(_ uiView: LineChartView, context: UIViewRepresentableContext<LineChartSwiftUI>) {

    }

    func setUpChart() {
        lineChart.noDataText = "No Data Available"
        let dataSets = [getLineChartDataSet()]
        let data = LineChartData(dataSets: dataSets)
        data.setValueFont(.systemFont(ofSize: 7, weight: .light))
        lineChart.data = data
    }

    func getChartDataPoints(sessions: [Int], accuracy: [Double]) -> [ChartDataEntry] {
        var dataPoints: [ChartDataEntry] = []
        for count in (0..<sessions.count) {
            dataPoints.append(ChartDataEntry.init(x: Double(sessions[count]), y: accuracy[count]))
        }
        return dataPoints
    }

    func getLineChartDataSet() -> LineChartDataSet {
        let dataPoints = getChartDataPoints(sessions: [0,1,2], accuracy: [100.0, 20.0, 30.0])
        let set = LineChartDataSet(entries: dataPoints, label: "DataSet")
        set.lineWidth = 2.5
        set.circleRadius = 4
        set.circleHoleRadius = 2
        let color = ChartColorTemplates.vordiplom()[0]
        set.setColor(color)
        set.setCircleColor(color)
        return set
    }
}

struct GraphSwiftUI_Previews: PreviewProvider {
    static var previews: some View {
        GraphSwiftUI()
    }
}

Upvotes: 13

Related Questions