问题描述
一般而言,我了解使对象符合UIViewRepresentable
的想法,但在实践中仍难以进行。
let chartView = OCKCartesianChartView(type: .bar)
chartView.headerView.titleLabel.text = "Doxylamine"
chartView.graphView.dataSeries = [
OCKDataSeries(values: [0,1,2,3,2],title: "Doxylamine")
]
因此,在符合init(type)
的结构中,需要将headerView.titleLabel
,graphView.dataSeries
和@Binding
设置为UIViewRepresentable
变量,但是我很努力弄清楚如何使用以下两个功能:
func makeUIView() {}
func updateUIView() {}
任何帮助将不胜感激。
解决方法
实际上只有数据需要绑定,因为类型是初始化的一部分,并且标题几乎不可能更改,所以这里是可能的变体
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
}
}