Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read all NSAttributedString attributes with their effective range

I am working on project which required to to find range of bold words in textview and replace their colour, I have already tried the following but it did not work.

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

}
like image 682
user3395433 Avatar asked Dec 30 '25 21:12

user3395433


1 Answers

The value argument passed to the closure of enumerateAttribute with NSFontAttributeName represents a UIFont bound to the range. So, you just need to check if the font is bold or not and collect the 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)
        }
    }
}

The you can change the color in those ranges in a normal way:

//Replace their colors.
let mutableAttributedText = attributedText.mutableCopy() as! NSMutableAttributedString
for boldRange in boldRanges {
    mutableAttributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: boldRange)
}
descriptionTextView.attributedText = mutableAttributedText
like image 185
OOPer Avatar answered Jan 04 '26 18:01

OOPer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!