Search code examples
iosswiftswiftuiuiviewrepresentablecarekit

How to make CareKitUI Bar Charts compatible with SwiftUI


Currently, there is limited support for CareKit using SwiftUI.

I understand, generally, the idea of making an object conforming to UIViewRepresentable, but am struggling to get going with how this would work in practice.

The following is example code from the readme:

let chartView = OCKCartesianChartView(type: .bar)

chartView.headerView.titleLabel.text = "Doxylamine"

chartView.graphView.dataSeries = [
    OCKDataSeries(values: [0, 1, 1, 2, 3, 3, 2], title: "Doxylamine")
]

So the init(type), headerView.titleLabel and graphView.dataSeries would need to be set as @Binding variables in a struct conforming to UIViewRepresentable, but I'm struggling to figure out how I have to use the following two functions:

func makeUIView() {}

func updateUIView() {}

Any help would be much appreciated.


Solution

  • Actually only data requires binding, because type is part of initialization and title is hardly possible to be changed, so here is possible variant

    struct CartesianChartView: UIViewRepresentable {
        var title: String
        var type: OCKCartesianGraphView.PlotType = .bar
        @Binding var data: [OCKDataSeries]
    
        func makeUIView(context: Context) -> OCKCartesianChartView {
            let chartView = OCKCartesianChartView(type: type)
    
            chartView.headerView.titleLabel.text = title
            chartView.graphView.dataSeries = data
    
            return chartView
        }
    
        func updateUIView(_ uiView: OCKCartesianChartView, context: Context) {
            // will be called when bound data changed, so update internal 
            // graph here when external dataset changed
            uiView.graphView.dataSeries = data
        }
    }