365SplendidSuns 365SplendidSuns - 2 years ago 182
iOS Question

Custom Swift NSNumberFormatterStyle

I'm using iOS charts to chart some data in my Swift iOS app including some times. The times are stored in Int variables as seconds but obviously people don't want to see 1 hour and 45 minutes on the Y axis as 6300 so I need to format it.

iOS charts lets you set use an NSNumberFormatter to do this like so

var formatter: NSNumberFormatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.SpellOutStyle
chartHolder.leftAxis.valueFormatter = formatter

But none of the styles available are suitable for what I need. I need it take a number of seconds and turn into, for example, 1h 45m. So I want to make a custom NSNumberFormatterStyle... But how do I do this?

Any help would be much appreciated.

Answer Source

This won't work with an NSNumberFormatterStyle - its options are too limited for you. What you should do, is subclass NSNumberFormatter, and override the stringFromNumber: function. There you can do all the string manipulation you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download