读取所有NSAttributedString属性及其有效范围

use*_*433 2 nsattributedstring swift3

我正在开发项目,需要在textview中找到一系列大胆的单词并替换它们的颜色,我已经尝试过以下但是它没有用.

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

}
Run Code Online (Sandbox Code Playgroud)

OOP*_*Per 8

value传递给enumerateAttributewith 的闭包的参数NSFontAttributeName代表了一个UIFont约束range.因此,您只需检查字体是否为粗体并收集范围.

//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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以以正常方式更改这些范围中的颜色:

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