Search code examples
iosswiftchartsaxis-labelsios-charts

How to set a custom x axis 0 label in charts ios


I am using Charts by Daniel Gindi

How can I set a String 0 label on x Axis? I want it to show "Now" instead of a Date type. I've seen the function that helps to format one particular label only, but I can't get how it works. Moreover, I haven't seen any examples of it. So, how does getFormattedLabel(index: Int) work? This is what I need my xAxis to look like: Example of what I need

Thank you!


Solution

  • This is a snippet that helps me convert an X axis into timeline and also make the last label on the chart of a String type.

    index == count - 2 was used because the label count on X axis was set to 3 by force:

    chart.xAxis.setLabelCount(3, force: true)
    chart.xAxis.avoidFirstLastClippingEnabled = false
    chart.xAxis.forceLabelsEnabled = true
    
    class ChartXAxisFormatter: NSObject, IAxisValueFormatter {
    
        func stringForValue(_ value: Double, axis: AxisBase?) -> String {
    
            if let index = axis?.entries.firstIndex(of: value), let count = axis?.entries.count  , index == count - 2 {
                return "Now"
            }
    
            let dateFormatterPrint = DateFormatter()
            dateFormatterPrint.dateFormat = "HH:mm:ss"
    
            let date = Date(timeIntervalSince1970: value)
            let time = dateFormatterPrint.string(from: date)
    
                return time
          }
    }