0

I am using Charts library by Daniel Gindi: https://github.com/danielgindi/Charts

For my project, I need to replace the x axis with time that shows only hours and minutes (HH:mm).

I've created the class with an extension based on this answer: 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)
       }

}

I have one Charts view that shows a pressure or temperature chart when I click on the particular button (there are separate buttons for showing temperature/pressure).

So, my question is that I can't figure out how I can actually use this class to transform my x axis to show time?

Any ideas? Thank you!

Lilya
  • 495
  • 6
  • 20

1 Answers1

0

Firstly, the class I mentioned above needs some update:

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

}

Secondly, I forgot to use this to actually connect xAxis value formatter to a new class:

chartView.chart.xAxis.valueFormatter = ChartXAxisFormatter() 
Lilya
  • 495
  • 6
  • 20