Search code examples
swift3nsattributedstring

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

}

Solution

  • 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