2016-03-06 109 views
0

(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

是的,它只是擔心字符數,因爲它是一個字符串方法。它現在知道你想用來顯示它們的字體。這種方法只能用於等寬字體,例如打印到控制檯時。保持標籤和值字符串分開,併爲它們使用不同的標籤。 – Sulthan

+0

是的,我做了一個使用兩個UITextViews的工作,但現在他們不滾動 – user5705847

+1

不要使用「填充」。使用NSAttributedString和選項卡。 – matt

回答

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 

它們對齊在小數點。我還沒有找到如何添加主要的點。如果有人這樣做,請隨時編輯我的答案。