iOS Charts ValueFormatter

我与影子孤独终老i 提交于 2019-12-04 12:11:27

Almost there, just need to add the following class:

class ChartValueFormatter: NSObject, IValueFormatter {
    fileprivate var numberFormatter: NumberFormatter?

    convenience init(numberFormatter: NumberFormatter) {
        self.init()
        self.numberFormatter = numberFormatter
    }

    func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
        guard let numberFormatter = numberFormatter
            else {
                return ""
        }
        return numberFormatter.string(for: value)!
    }
}

Now use this as the number formatter:

let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.locale = Locale.current
let valuesNumberFormatter = ChartValueFormatter(numberFormatter: numberFormatter)
lineChartDataSet.valueFormatter = valuesNumberFormatter
lineChartDataSet.valueFont = lineChartDataSet.valueFont.withSize(chartFontPointSize)
   lineChartDataSet.valueFormatter = DefaultValueFormatter(decimals: 2)
 let data = PieChartData(dataSet: set) 

 let formatter = NumberFormatter() 
 formatter.numberStyle = .percent 
 formatter.maximumFractionDigits = 2 
 formatter.multiplier = 1.0 
 formatter.percentSymbol = "%" 
 formatter.zeroSymbol = "" 
 data.setValueFormatter(DefaultValueFormatter(formatter: formatter))

This worked for me:

Swift 5

let valFormatter = NumberFormatter()
valFormatter.numberStyle = .currency
valFormatter.maximumFractionDigits = 2
valFormatter.currencySymbol = "$"

lineChartPrice.leftAxis.valueFormatter = DefaultAxisValueFormatter(formatter: valFormatter)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!