DefaultAxisValueFormatter.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //
  2. // DefaultAxisValueFormatter.swift
  3. // Charts
  4. //
  5. // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
  6. // A port of MPAndroidChart for iOS
  7. // Licensed under Apache License 2.0
  8. //
  9. // https://github.com/danielgindi/Charts
  10. //
  11. import Foundation
  12. @objc(ChartDefaultAxisValueFormatter)
  13. open class DefaultAxisValueFormatter: NSObject, AxisValueFormatter
  14. {
  15. public typealias Block = (
  16. _ value: Double,
  17. _ axis: AxisBase?) -> String
  18. @objc open var block: Block?
  19. @objc open var hasAutoDecimals: Bool = false
  20. private var _formatter: NumberFormatter?
  21. @objc open var formatter: NumberFormatter?
  22. {
  23. get { return _formatter }
  24. set
  25. {
  26. hasAutoDecimals = false
  27. _formatter = newValue
  28. }
  29. }
  30. // TODO: Documentation. Especially the nil case
  31. private var _decimals: Int?
  32. open var decimals: Int?
  33. {
  34. get { return _decimals }
  35. set
  36. {
  37. _decimals = newValue
  38. if let digits = newValue
  39. {
  40. self.formatter?.minimumFractionDigits = digits
  41. self.formatter?.maximumFractionDigits = digits
  42. self.formatter?.usesGroupingSeparator = true
  43. }
  44. }
  45. }
  46. public override init()
  47. {
  48. super.init()
  49. self.formatter = NumberFormatter()
  50. hasAutoDecimals = true
  51. }
  52. @objc public init(formatter: NumberFormatter)
  53. {
  54. super.init()
  55. self.formatter = formatter
  56. }
  57. @objc public init(decimals: Int)
  58. {
  59. super.init()
  60. self.formatter = NumberFormatter()
  61. self.formatter?.usesGroupingSeparator = true
  62. self.decimals = decimals
  63. hasAutoDecimals = true
  64. }
  65. @objc public init(block: @escaping Block)
  66. {
  67. super.init()
  68. self.block = block
  69. }
  70. @objc public static func with(block: @escaping Block) -> DefaultAxisValueFormatter?
  71. {
  72. return DefaultAxisValueFormatter(block: block)
  73. }
  74. open func stringForValue(_ value: Double,
  75. axis: AxisBase?) -> String
  76. {
  77. if let block = block {
  78. return block(value, axis)
  79. } else {
  80. return formatter?.string(from: NSNumber(floatLiteral: value)) ?? ""
  81. }
  82. }
  83. }