1

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.

GarethPrice
  • 1,072
  • 2
  • 14
  • 25

1 Answers1

1

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
    }
}
GarethPrice
  • 1,072
  • 2
  • 14
  • 25
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • thanks! However, when I do the following: `CartesianChartView(title: "Glucose", data: OCKDataSeries(values: [0, 1, 1, 2, 3, 3, 2], title: "Doxylamine"))` it returns an error with `Cannot convert value of type 'OCKDataSeries' to expected argument type 'Binding<[OCKDataSeries]>'`. How do I correct this? – GarethPrice Oct 03 '20 at 11:43
  • 1
    If you don't want to change data later then remove `@Binding` as use it as regular property, otherwise put data either in `@State` property in parent or in some `ObservableObject` view model. – Asperi Oct 03 '20 at 13:45