swift - 使用 Daniel Gindi 的 Charts 库在图表的 x 轴上显示时间
问题描述
我正在使用 Daniel Gindi 的图表库:https ://github.com/danielgindi/Charts
对于我的项目,我需要将 x 轴替换为仅显示小时和分钟 (HH:mm) 的时间。
我已经根据这个答案创建了一个带有扩展名的类:ios Charts 3.0 - Align x labels (dates) with plots
import UIKit
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)
}
}
我有一个图表视图,当我单击特定按钮时显示压力或温度图表(有单独的按钮用于显示温度/压力)。
所以,我的问题是我不知道如何实际使用这个类来转换我的 x 轴以显示时间?
有任何想法吗?谢谢!
解决方案
首先,我上面提到的类需要一些更新:
import UIKit
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 {
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "HH:mm"
let date = Date(timeIntervalSince1970: value)
return dateFormatterPrint.string(from: date)
}
}
其次,我忘记使用它来实际将 xAxis 值格式化程序连接到一个新类:
chartView.chart.xAxis.valueFormatter = ChartXAxisFormatter()
推荐阅读
- javascript - How i can do a function who can be applied to any variables at the end of the variable?
- swift - 无法正确隐藏到 UINavigationBar
- c# - 如何使用密码授予流程更改 IdentityServer4 的默认错误消息
- java - 流口水规则语法中的异常
- bing-api - Bing API 相关搜索
- python - ValueError:SavedModel 的 SignatureDefs 中没有“serving_default”。可能的值为“name_of_my_model”
- c++ - 命名空间:不能调用没有对象的成员函数
- python - DetailView 包含来自其他两个模型的数据
- angular - FormGroup 不适用于带有 Angular 7 的 Ionic
- angular - 角度 svg 图像预览