365SplendidSuns 365SplendidSuns - 3 months ago 36
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

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.