您必须使用IAxisValueFormatter
来显示 xAxis 上的值
我创建了以下课程
class BarChartFormatter: NSObject,IAxisValueFormatter,IValueFormatter {
var values : [String]
required init (values : [String]) {
self.values = values
super.init()
}
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return values[Int(value)]
}
func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
return values[Int(entry.x)]
}
}
如下更新您的方法
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(x: Double(i), y: values[i])
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: nil)
ChartIMG.chartDescription?.enabled = false
self.ChartIMG.legend.enabled = false
let formatter = BarChartFormatter(values: dataPoints)
let xAxis = XAxis()
xAxis.valueFormatter = formatter
ChartIMG.xAxis.valueFormatter = xAxis.valueFormatter
let chartData = BarChartData(dataSet: chartDataSet)
ChartIMG.data = chartData
希望对您有所帮助
或者
我已经创建了一个可以使用的扩展只需复制并粘贴新的 swift 文件
import Charts
extension BarChartView {
private class BarChartFormatter: NSObject,IAxisValueFormatter {
var values : [String]
required init (values : [String]) {
self.values = values
super.init()
}
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return values[Int(value)]
}
}
func setChartValues (xAxisValues : [String] , values : [Double],label : String) {
var barChartDataEntries = [BarChartDataEntry]()
for i in 0..<values.count {
let dataEntry = BarChartDataEntry(x: Double(i), y: values[i])
barChartDataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: barChartDataEntries, label: label)
chartDataSet.colors = ChartColorTemplates.colorful()
let chartData = BarChartData(dataSet: chartDataSet)
let formatter = BarChartFormatter(values: xAxisValues)
let xAxis = XAxis()
xAxis.valueFormatter = formatter
self.xAxis.valueFormatter = xAxis.valueFormatter
self.xAxis.labelPosition = .bottom
self.data = chartData
self.data?.notifyDataChanged()
self.notifyDataSetChanged()
self.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .linear)
}
}
你可以像这样使用它
@IBOutlet weak var barChartView: BarChartView!
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
let unitsSold = [20.0, 4.0, 3.0, 6.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0]
self.barChartView.setChartValues(xAxisValues: months, values: unitsSold, label: "Monthly Sales")