2016-07-24 10 views
3

特定の属性を適用するテキスト用語の文字列を含むarraysがあります。コードスニペットは次のとおりです。スイフト。複数のインスタンスに属性を追加する

static var bold = [String]() 
static let boldAttribs = [NSFontAttributeName: UIFont(name: "WorkSans-Medium", size: 19)!] 
for term in bold { 
    atStr.addAttributes(boldAttribs, range: string.rangeOfString(term)) 
} 

これは、単語句の使用に最適です。しかし、それは特定の用語の最初の使用にのみ適用されます。同じ期間のすべてのインスタンスに属性を適用する方法はありますか?たとえば、同じ文字列内の「アニメーションボタン」を使用するたびに太字にします。

編集:これは機能します。

// `butt2` is [String]() of substrings to attribute 
// `term` is String element in array, target of attributes 
// `string` is complete NAString from data 
// `atStr` is final 
for term in butt2 { 
    var pos = NSRange(location: 0, length: string.length) 
    while true { 
     let next = string.rangeOfString(term, options: .LiteralSearch, range: pos) 
     if next.location == NSNotFound { break } 

     pos = NSRange(location: next.location+next.length, length: string.length-next.location-next.length) 

     atStr.addAttributes(butt2Attribs, range: next) 
    } 
} 

答えて

2

あなたは数値範囲に頼る必要はありませんが、ループに頼る必要がありますか:

// atStr is mutable attributed string 
// str is the input string 
atStr.beginEditing() 
var pos = NSRange(location: 0, length: atStr.length) 
while true { 
    let next = atStr.rangeOfString(target, options: .LiteralSearch, range: pos) 
    if next.location == NSNotFound { 
     break 
    } 
    atStr.addAttributes(boldAttribs, range: next) 
    print(next) 
    pos = NSRange(location: next.location+next.length, length: atStr.length-next.location-next.length) 
} 
atStr.endEditing() 
+0

これはタイプレンジ bpedit

+0

@bpeditこれはこれを修正するはずですが、NSRange APIは少し異なります。コンパイラからの「かわいい」ビルトインサポートはありません。 – dasblinkenlight

+0

どちらも動作しません。 'NSMutableString'はメンバ' string of string'を持っていません。私は本当にSwiftの 'String'を' atStr'に 'str'を使用したいと思いますが、私は最初のゴーラウンドと同じ変換の問題を抱えています。 – bpedit

関連する問題