轴上的值似乎是重复而不是被替换,正如您在下面的屏幕截图中看到的那样,它应该绘制" Jan"," 2月",&# 34; Mar"," Apr"," May"," Jun"而不是模拟器中的结果。
这是代码
class ViewController: UIViewController {
@IBOutlet weak var chartContainer: LineChartView!
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 3.0]
override func viewDidLoad() {
super.viewDidLoad()
setChart(dataPoints: months, values: unitsSold)
}
func setChart(dataPoints: [String], values: [Double]) {
// Set up x axis
let xaxis = XAxis()
let chartFormatter = ChartFormatter(myArr: months)
// Array for entries
var dataEntries: [ChartDataEntry] = []
// Add new data entries
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(x: Double(i) , y: values[i], data: "a" as AnyObject? )
dataEntries.append(dataEntry)
chartFormatter.stringForValue(Double(i), axis: xaxis)
}
xaxis.valueFormatter = chartFormatter
chartContainer.xAxis.valueFormatter = xaxis.valueFormatter
// Configure the dataset
let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Units Sold")
let lineChartData = LineChartData(dataSet: lineChartDataSet)
chartContainer.data = lineChartData
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
@objc(ChartFormatter)
class ChartFormatter: NSObject, IAxisValueFormatter {
private var myArr: [String]!
init(myArr: [String]) {
self.myArr = myArr
}
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return myArr[Int(value)]
}
}
答案 0 :(得分:4)
我自己通过添加
解决了这个问题 chartContainer.xAxis.granularityEnabled = true
chartContainer.xAxis.granularity = 1.0