Custom Swift NSNumberFormatterStyle
I am using iOS charts to chart some data in my Swift iOS app including multiple times. The time is stored in Int variables as seconds, but obviously people don't want to see the 1st and 45th minutes on the Y-axis as 6300, so I need to format it.
iOS diagrams allow you to use NSNumberFormatter to do it like this
var formatter: NSNumberFormatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.SpellOutStyle
chartHolder.leftAxis.valueFormatter = formatter
But none of the available styles are suitable for what I need. I need it to take a few seconds and turn on for example 1h 45m. So I want to create a custom NSNumberFormatterStyle ... But how should I do this?
Any help would be much appreciated.
source to share
This won't work with NSNumberFormatterStyle - its options are too limited for you. What you have to do is subclass NSNumberFormatter
and override the function stringFromNumber:
. There you can do all the necessary string manipulations.
source to share
A good way to do this is to create a subclass for you NSNumberFormatter
and use within it NSDateFormatter
to generate string output from your number. Here's an example:
class ElapsedTimeFormatter: NSNumberFormatter {
lazy var dateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
return dateFormatter
}()
override func stringFromNumber(number: NSNumber) -> String? {
let timeInterval = NSTimeInterval(number)
return dateFormatter.stringFromDate(NSDate(timeIntervalSinceReferenceDate: timeInterval))
}
}
Test:
let formatter = ElapsedTimeFormatter()
let s = formatter.stringFromNumber(6300)
// Output: s = "01:45"
source to share