2017-12-12 6 views
0

属性の文字列を使用して、UILabelのタブのデフォルト幅を変更したいとします。それをどうすれば実現できますか?私は、属性NSMutableParagraphStyleを追加する必要があると仮定しますが、どのプロパティがタブの長さの原因であるかわかりません。NSAttributedStringの " t"長さを変更するにはどうすればよいですか?

のは、例えば、このコードを使用してみましょう:

let text = "test\ttest" 
let attributedText = NSMutableAttributedString(string: text) 
let paragraphStyle = NSMutableParagraphStyle() 
let textRange = NSRange(location: 0, length: text.length) 
attributedText.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: textRange) 
+0

に割り当てる必要がありいくつのスペースを追加しようとしていますか? – DoesData

+0

たとえば、私が8ポイントのスペースを必要としているとします。問題は、テキストの色分けです。 " – ThirdMartian

答えて

2

をしたいスペースの数で\ tを交換しようとすることができ、var tabStops: [NSTextTab]!を表すNSTextTabオブジェクトの配列です受信者のタブが停止します。あなたは、タブにアクセスし、次のように自分の位置を変更することができます

let paragraphStyle = NSMutableParagraphStyle() 
paragraphStyle.tabStops = [NSTextTab(textAlignment: .left, location: newTabLength, options: [:])] 

label.attributedText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName: paragraphStyle]) 
+0

これは私が望んだものです。 – ThirdMartian

1

あなたはApple Developer Documentationによると、あなたが

var text = "test\ttest" 
text = text.replacingOccurrences(of: "\\t", with: " ") 
let attributedText = NSMutableAttributedString(string: text) 
let paragraphStyle = NSMutableParagraphStyle() 
let textRange = NSRange(location: 0, length: text.length) 
attributedText.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: textRange) 
+0

1つのスペースを追加すると同じ結果をいくつか追加します。 " – ThirdMartian

+0

はいhtmlはスペースを避ける –

2

タブストップの長さを変更するにはNSMutableParagraphStyleを経由してあなたがNSTextTabインスタンスの新しい配列を作成し、tabStops配列

let text = "test\ttest\ttest" 
let attributedText = NSMutableAttributedString(string: text) 
let paragraphStyle = NSMutableParagraphStyle() 
let tabInterval : CGFloat = 40.0 
var tabs = [NSTextTab]() 
for i in 1...10 { tabs.append(NSTextTab(textAlignment: .left, location: tabInterval * CGFloat(i))) } 
paragraphStyle.tabStops = tabs 
let textRange = NSRange(location: 0, length: text.count) 
attributedText.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: textRange) 
+0

答えてくれてありがとう、残念なことに@Dorukhan Arslanがまず無駄に、私は彼の答えを受け入れるだろう。 – ThirdMartian

+1

@ThirdMartian問題ありません – vadian

+0

帰属するテキストのタブ文字の長さを私の答えの最初のタブのみに変更する方法を示しました。 @ vadianの答えは、次のタブにも同様に適用できる優れた拡張機能を提供します。 –

関連する問題