iOS Charts ValueFormatter

后端 未结 4 1200
天命终不由人
天命终不由人 2021-02-15 19:04

I am using iOS charts plugin (line chart) and wish to style the chart values (the number above each point) to a decimal number.

The value is a double, but charts by defa

相关标签:
4条回答
  • 2021-02-15 19:13
     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))
    
    0 讨论(0)
  • 2021-02-15 19:16

    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)
    
    0 讨论(0)
  • 2021-02-15 19:28
       lineChartDataSet.valueFormatter = DefaultValueFormatter(decimals: 2)
    
    0 讨论(0)
  • 2021-02-15 19:31

    This worked for me:

    Swift 5

    let valFormatter = NumberFormatter()
    valFormatter.numberStyle = .currency
    valFormatter.maximumFractionDigits = 2
    valFormatter.currencySymbol = "$"
    
    lineChartPrice.leftAxis.valueFormatter = DefaultAxisValueFormatter(formatter: valFormatter)
    
    0 讨论(0)
提交回复
热议问题