【问题标题】:Show time on x axis of the chart using Charts library by Daniel Gindi使用 Daniel Gindi 的 Charts 库在图表的 x 轴上显示时间
【发布时间】:2020-03-12 13:56:56
【问题描述】:

我正在使用 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 轴以显示时间?

有什么想法吗?谢谢!

【问题讨论】:

    标签: swift xcode charts ios-charts


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      相关资源
      最近更新 更多