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
帰属テキスト以外の方法はありますか? – user3395433