How can I make a chart view using Charts library in SwiftUI
In other words, how to make a UIViewRepresentable
for it?
Let's start building such bar chart in SwiftUI step-by-step. First, we need to declare three customization properties and one data set property. import SwiftUI struct BarChart: View { var title: String var legend: String var barColor: Color var data: [ChartData] var body: some View { Text("Hello, World!") } }
Open Xcode and select Create a new Xcode project. And then fill in the details for the new project, let's name the app “RestaurantMenu” and make sure you've selected SwiftUI for the User Interface. And click Next. And then choose your preferred directory and click on Create to create your new Project.
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()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With