2016-12-07 5 views
1

私はtextviewで大胆な単語の範囲を見つけて色を置き換える必要があるプロジェクトに取り組んでいますが、私はすでに以下を試してみましたが動作しませんでした。 NSFontAttributeNameenumerateAttributeの閉鎖に渡さすべてのNSAttributedString属性の有効範囲を読み取る

.enumerateAttribute (NSFontAttributeName, in:NSMakeRange(0, descriptionTextView.attributedText.length), options:.longestEffectiveRangeNotRequired) { value, range, stop in 

} 
+0

帰属テキスト以外の方法はありますか? – user3395433

答えて

5

value引数はrangeにバインドUIFontを表します。したがって、フォントが太字かどうかをチェックして範囲を収集するだけで済みます。

//Find ranges of bold words. 
let attributedText = descriptionTextView.attributedText! 
var boldRanges: [NSRange] = [] 
attributedText.enumerateAttribute(NSFontAttributeName, in: NSRange(0..<attributedText.length), options: .longestEffectiveRangeNotRequired) { 
    value, range, stop in 
    //Confirm the attribute value is actually a font 
    if let font = value as? UIFont { 
     //print(font) 
     //Check if the font is bold or not 
     if font.fontDescriptor.symbolicTraits.contains(.traitBold) { 
      //print("It's bold") 
      //Collect the range 
      boldRanges.append(range) 
     } 
    } 
} 

あなたは、通常の方法でこれらの範囲内の色を変更することができザ・:上記の壮大な答えは、これを実行するだけで、詳細なコード・フラグメントに基づいて

//Replace their colors. 
let mutableAttributedText = attributedText.mutableCopy() as! NSMutableAttributedString 
for boldRange in boldRanges { 
    mutableAttributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: boldRange) 
} 
descriptionTextView.attributedText = mutableAttributedText 
+0

うわー。貴重な投稿、ありがとう。 – Fattie

1

xは、可変属性の文字列です。誰かが何らかの入力を省くことを願っています。

let f = UIFont.systemFont(ofSize: 20) 
let fb = UIFont.boldSystemFont(ofSize: 20) 
let fi = UIFont.italicSystemFont(ofSize: 20) 

let rangeAll = NSRange(location: 0, length: x.length) 

var boldRanges: [NSRange] = [] 
var italicRanges: [NSRange] = [] 

x.beginEditing() 
print("----------------------->") 

x.enumerateAttribute(
     NSFontAttributeName, 
     in: rangeAll, 
     options: .longestEffectiveRangeNotRequired) 
      { value, range, stop in 

      if let font = value as? UIFont { 
       if font.fontDescriptor.symbolicTraits.contains(.traitBold) { 
        print("It's bold!") 
        boldRanges.append(range) 
       } 
       if font.fontDescriptor.symbolicTraits.contains(.traitItalic) { 
        print("It's italic!") 
        italicRanges.append(range) 
       } 
      } 
     } 

x.setAttributes([NSFontAttributeName: f], range: rangeAll) 

for r in boldRanges { 
    x.addAttribute(NSFontAttributeName, value: fb, range: r) 
} 
for r in italicRanges { 
    x.addAttribute(NSFontAttributeName, value: fi, range: r) 
} 

print("<-----------------------") 
using.cachedAttributedString?.endEditing() 

注 - この例両方太字やイタリックの迷惑な場合とない取引を行います!私はこれがもっと有益だと思った。

関連する問題