Charts lineChartDataset rounded values

2019-02-14 10:46发布

问题:

I'm trying out a few things with the iOS Charts library with Swift 3.0. I have a question about formatting of the lineChartDataset values (displayed above each value point). Right now these values are 'double' and are displayed as 2.0 and 3.0 instead of just 2 and 3 etc. Is it possible to round these values? I tried with numberFormatter but nothing works. Any help would be appreciated.

回答1:

ios-charts have been upgraded to protocol base approach for rendering the various kind of labels like xAxis, yAxis etc. So you have to implement protocol IValueFormatter in order to achieve the required results. I have created the class for the same, so directly use this as below & you would be able to achieve desired results.

Create a class named as DigitValueFormatter & assign that to LineChartData object as lineChartData.setValueFormatter(DigitValueFormatter())

import Foundation
import Charts

class DigitValueFormatter : NSObject, IValueFormatter {

    func stringForValue(_ value: Double,
                        entry: ChartDataEntry,
                        dataSetIndex: Int,
                        viewPortHandler: ViewPortHandler?) -> String {
        let valueWithoutDecimalPart = String(format: "%.0f", value)
        return "\(valueWithoutDecimalPart)"
    }
}