Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Chart with Date / Time on the bottom Axis using iOS Charts Library?

I am currently working with the iOS Library Charts and have some issues to implement a TimeLine for the x Axis.

Library Link: https://github.com/danielgindi/Charts

I have a List of Objects as the Input for the Chart.

let objectList : [Object] = fillObjectList()

class Object {
    var timeCreated : Date
    var value : Double
}

I already implemented a solution where I just used the timeCreated.timeIntervalsince1970 as the values for the x Axis. But this does not look so great.

So if some of you have some experience using iOS Charts Library, I hope you guys can think of a solution for this problem. Thanks a lot for your help in advance!

like image 619
christophriepe Avatar asked Apr 19 '20 10:04

christophriepe


1 Answers

You need to create implementation class of IAxisValueFormatter, something like this

note: I did not compile it, so may need some correction

public class DateValueFormatter: NSObject, IAxisValueFormatter {
    private let dateFormatter = DateFormatter()
    private let objects:[Object]
    
    init(objects: [Object]) {
        self.objects = objects
        super.init()
        dateFormatter.dateFormat = "dd MMM HH:mm"
    }
    
    public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        if value >= 0 && value < objects.count{
            let object = objects[Int(value)]
            return dateFormatter.string(from: object.timeCreated)
        }   
        return ""
    }
}

and use the formatted with this code

xAxis.valueFormatter = DateValueFormatter(objects: objectList)

edit: you can see some example what I try using charts lib in this repo

like image 110
aiwiguna Avatar answered Nov 16 '22 17:11

aiwiguna