如何在SwiftUI中使用Charts库创建图表视图
换句话说,如何为此制作一个UIViewRepresentable
?
答案 0 :(得分:0)
以下是一些示例代码,可以帮助您入门。不知道这是否是最佳实践,但这是让我熟悉Charts和SwiftUI的最简单方法。希望这会有所帮助!
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()
}
}
答案 1 :(得分:0)
如果您希望每次数据更改时都更新图的视图,请在设置位置添加一个UpdateData()
函数,并返回LineChartData()
对象。
然后设置uiView.data = UpdateData()
并致电uiView.notifyDataSetChanged()
。
这应该重新呈现您的图形。