首页 > 解决方案 > 使用 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 轴以显示时间?

有任何想法吗?谢谢!

标签: swiftxcodechartsios-charts

解决方案


首先,我上面提到的类需要一些更新:

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() 

推荐阅读