How can I get a Decimal Tab Stop on iOS when NSTextTab on iOS doesn't offer that option?

320 Views Asked by At

When developing for OS X, you have the option of specifying the DecimalTabStopType to get a tab stop on the decimal point of a column of numbers. However, this option isn't available in iOS - is there some way to achieve the same affect?

2

There are 2 best solutions below

1
On BEST ANSWER

Currently there's a built-in support for decimal tab stops, see https://developer.apple.com/documentation/uikit/nstexttab/1535107-columnterminators

Can be used as follows

let paragraphStyle = NSMutableParagraphStyle()
let terms = NSTextTab.columnTerminators(for: NSLocale.current)
let tabStop0 = NSTextTab(textAlignment: .right, location: 100, options: 
[NSTabColumnTerminatorsAttributeName:terms])
0
On

With a little bit of effort, you can easily achieve the same effect on iOS. First, you add a Right tab stop. Then, you add a Left tab stop a very tiny bit to the right. [It appears that the tabStop array is sorted by their offset, so you cannot use exactly the same offset.]

let centerTab = NSTextTab(textAlignment: .Right, location: width - 100, options: [:])
let leftTab = NSTextTab(textAlignment: .Left, location: width - 100 + 0.001, options: [:])

When you have a plan number - no decimal point - you would append text of "value\t" - the value is aligned to the left of the first tab stop, then the tab character takes you to the next tab. If you have a string with a decimal point, split the string into two parts, and then pass the string "firstPart" + "\t + "." "secondPart".

let nString: String
if case let array = item.value.componentsSeparatedByString(".") where array.count == 2 {
   nString = array[0] + "\t." + array[1]
} else {
   nString = item.value + "\t"
}
// append nString

You can also use this to align numbers some of which are values and others which have trailing percent signs (using similar techniques).