Swift字符串填充不相等?

时间:2016-03-06 01:08:54

标签: string swift

(SWIFT)

当使用String.stringByPaddingToLength时,它正确填充到设定的字符数,但不同的行具有不同的填充位置,因为某些字符比其他字符大。

发生了什么......(不等间距)

SomeValueName:..................SomeValue  (40 characters wide)

SomeDifferentValue..........SomeValue (40 characters wide)

我需要什么(等间距)

someValueName:..............SomeValue (40 characters wide)

someDifferentValue...........SomeValue (40 characters wide)

我是否无法使用stringByPaddingToLength来获得此结果?好像它只是担心字符数量实际上并不是它最终的位置。

1 个答案:

答案 0 :(得分:0)

使用标签来对齐字符串:

let paragraphStyle = NSMutableParagraphStyle()
let terminator = NSTextTab.columnTerminatorsForLocale(NSLocale.currentLocale())
// Adjust the location as needed for your text
let tab = NSTextTab(textAlignment: .Right, location: 72.0 * 2, options: [NSTabColumnTerminatorsAttributeName: terminator])
paragraphStyle.tabStops = [tab]

let attributedString = NSMutableAttributedString(string: "Apple:\t$1.50\nOrange:\t$1", attributes: [NSParagraphStyleAttributeName: paragraphStyle])
self.textView.attributedText = attributedString

打印:

Apple:         $1.5
Orange:        $1

它们在小数点对齐。我还没有找到如何添加前导点。如果有人这样做,请随时编辑我的答案。