我很难将库图表(来自Daniel Gindi)从版本2(Swift 2.3)迁移到3(Swift 3).
基本上,我不能让x标签(日期)与相应的图正确对齐.
这是我之前在第2版中所拥有的:
在版本2中,我有第7天,第8天,第10天和第11天的值.所以我错过了中间的一天,但标签正确地与图表一起使用.
这是我在版本3中的内容:
在版本3中,x轴中的"标签"现在已被替换为double(对于日期,它是自1970年以来的timeInterval),并通过格式化程序进行格式化.因此,无可否认,图表现在更"正确",因为图表正确地推断出第9个值,但我找不到如何将标签放在相应的图表下面.
这是我的x轴代码:
let chartView = LineChartView() ... let xAxis = chartView.xAxis xAxis.labelPosition = .bottom xAxis.labelCount = entries.count xAxis.drawLabelsEnabled = true xAxis.drawLimitLinesBehindDataEnabled = true xAxis.avoidFirstLastClippingEnabled = true // Set the x values date formatter let xValuesNumberFormatter = ChartXAxisFormatter() xValuesNumberFormatter.dateFormatter = dayNumberAndShortNameFormatter // e.g. "wed 26" xAxis.valueFormatter = xValuesNumberFormatter
这是我创建的ChartXAxisFormatter类:
import Foundation import Charts class ChartXAxisFormatter: NSObject { var dateFormatter: DateFormatter? } extension ChartXAxisFormatter: IAxisValueFormatter { func stringForValue(_ value: Double, axis: AxisBase?) -> String { if let dateFormatter = dateFormatter { let date = Date(timeIntervalSince1970: value) return dateFormatter.string(from: date) } return "" } }
因此,这里的值是正确的,格式是正确的,图表的形状是正确的,但标签与相应图的对齐并不好.谢谢你的帮助
好的,我知道了!
您必须定义参考时间间隔(x轴为"0").然后计算每个x值的附加时间间隔.
ChartXAxisFormatter变为:
import Foundation import Charts class ChartXAxisFormatter: NSObject { fileprivate var dateFormatter: DateFormatter? fileprivate var referenceTimeInterval: TimeInterval? convenience init(referenceTimeInterval: TimeInterval, dateFormatter: DateFormatter) { self.init() self.referenceTimeInterval = referenceTimeInterval self.dateFormatter = dateFormatter } } extension ChartXAxisFormatter: IAxisValueFormatter { func stringForValue(_ value: Double, axis: AxisBase?) -> String { guard let dateFormatter = dateFormatter, let referenceTimeInterval = referenceTimeInterval else { return "" } let date = Date(timeIntervalSince1970: value * 3600 * 24 + referenceTimeInterval) return dateFormatter.string(from: date) } }
然后,当我创建数据条目时,它的工作原理如下:
// (objects is defined as an array of struct with date and value) // Define the reference time interval var referenceTimeInterval: TimeInterval = 0 if let minTimeInterval = (objects.map { $0.date.timeIntervalSince1970 }).min() { referenceTimeInterval = minTimeInterval } // Define chart xValues formatter let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .none formatter.locale = Locale.current let xValuesNumberFormatter = ChartXAxisFormatter(referenceTimeInterval: referenceTimeInterval, dateFormatter: xValuesFormatter) // Define chart entries var entries = [ChartDataEntry]() for object in objects { let timeInterval = object.date.timeIntervalSince1970 let xValue = (timeInterval - referenceTimeInterval) / (3600 * 24) let yValue = object.value let entry = ChartDataEntry(x: xValue, y: yValue) entries.append(entry) } // Pass these entries and the formatter to the Chart ...
结果更好(我顺便删除了立方体):