Open owenzhao opened 2 years ago
// // ContentView.swift // Bar Chart Test // // Created by zhaoxin on 2022/4/28. // import SwiftUI import SwiftUICharts struct ContentView: View { @State var data:BarChartData? var body: some View { ScrollView { VStack { if let data = data { BarChart(chartData: data) .touchOverlay(chartData: data, specifier: "%0.f KGs") .xAxisGrid(chartData: data) .yAxisGrid(chartData: data) .xAxisLabels(chartData: data) .yAxisLabels(chartData: data, specifier: "%0.f KGs") .floatingInfoBox(chartData: data) .headerBox(chartData: data) .padding() HStack { Button { data.dataSets.dataPoints.removeFirst() data.dataSets.dataPoints.append(getRandomPoint()) } label: { Text("Append Item") } Button { changeMaxBarNumber() } label: { Text("Change Max Bar Number") } } } else { ProgressView().onAppear { let points = (1...10).map { _ in getEmptyPoint()} let barStyle = BarStyle(barWidth: 0.5, colourFrom: .dataPoints) data = BarChartData(dataSets: BarDataSet(dataPoints: points), barStyle: barStyle) } } } } .padding() .frame(minWidth: 800, minHeight: 350) } private func getRandomPoint() -> BarChartDataPoint { let i = Int.random(in: 50...100) return BarChartDataPoint(value: Double(i), xAxisLabel: String(i), colour: ColourStyle(colour: .green)) } private func getEmptyPoint() -> BarChartDataPoint { return BarChartDataPoint(value: 0, xAxisLabel: nil, colour: ColourStyle(colour: .green)) } private func changeMaxBarNumber() { let maxBarNumber = Int.random(in: 10...20) var points = data!.dataSets.dataPoints.filter { $0.value != 0 } let count = points.count guard let data = data else { fatalError() } if count < maxBarNumber { let emptyPoints = (1...(maxBarNumber - count)).map { _ in getEmptyPoint() } points.insert(contentsOf: emptyPoints, at: 0) data.dataSets = BarDataSet(dataPoints: points) } else { data.dataSets = BarDataSet(dataPoints: Array(points[(count - maxBarNumber)...])) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
https://user-images.githubusercontent.com/2182896/171357724-cb0414e5-8a55-4178-85c0-844794a50c8f.mov
https://user-images.githubusercontent.com/2182896/171357724-cb0414e5-8a55-4178-85c0-844794a50c8f.mov