我正在尝试创建一个包含去年数据的折线图。我想让图表的xAxis上的标签代表去年的月份,这在本教程中似乎很容易完成:https://www.codebeaulieu.com/96/How-to-create-a-Combined-Bar-and-Line-chart-using-ios-charts。但是,这一行代码来自教程:
let data: LineChartData = LineChartData(xVals: months, dataSets: dataSets)
其中“months”表示字符串数组,在图表更新到Swift 2.3后不可用。 LineChartData唯一可用的构造函数是这两个:
LineChartData(dataSets: <[IChartDataSet]?>)
LineChartData(dataSet: IChartDataSet?)
所以看起来更新后更改xVals的选项已消失。这个选项是否在其他地方移动了?或者是否已将其从iOS图表中完全删除?
答案 0 :(得分:1)
放弃一段时间后,我终于找到了解决方案。您必须制作IAxisValueFormatter
并实施stringForValue
功能。例如,我想格式化我的图表以显示基于当前月份的过去12个月。这是我的值格式化程序:
import UIKit
import Charts
class MonthNumberFormatter: NSObject, IAxisValueFormatter {
private let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
private var startMonthIndex:Int!
convenience init(startMonthIndex: Int){
self.init()
self.startMonthIndex = startMonthIndex
}
private func getMonth(index: Int) -> Int{
return (index % months.count)
}
func stringForValue(_ value: Double, axis: AxisBase?) -> String{
let monthIndex:Int = self.getMonth(index: Int(value) + self.startMonthIndex)
let month = months[monthIndex]
return month
}
}
然后在你的图表类中 - &gt;得到当月:
func getCurrentMonth()->Int? {
let todayDate = Date()
let myCalendar = NSCalendar(calendarIdentifier: .gregorian)
let myComponents = myCalendar?.components(.month, from: todayDate)
let month = myComponents?.month
return month
}
现在在图表上设置值
let xAxis = self.chartView.xAxis
let currentMonth = getCurrentMonth()
xAxis.valueFormatter = MonthNumberFormatter(startMonthIndex: currentMonth!)