Search code examples
iosswiftnsattributedstringnsmutableattributedstringnsrange

Add font to NSMutableAttributedString where .font attribute is missing


I want to apply a specific font to an NSMutableAttributedString where no .font attribute is applied. How could I achieve that? I tried enumerating the attributes that contain a font and extracting the ranges but I am kind of lost to the complexity of finding the ranges that don't contain a font attribute since I think I must handle intersections or possible unknown scenarios. Is there a simple way to do it? What I did until now:

        var allRangesWithFont = [NSRange]()
        let stringRange = NSRange(location: 0, length: length)
        
        beginEditing()
        enumerateAttribute(.font,
                           in: stringRange,
                           options: .longestEffectiveRangeNotRequired) { (value, range, stop) in
            
            if let f = value as? UIFont {
                allRangesWithFont.append(range)
            }
        }

Solution

  • Change your way of thinking, instead, check if the font is not there, and apply your new font directly.

    With attrStr being your NSMutableAttributedString, and newFont the font you want to apply.

    let newFont = UIFont.italicSystemFont(ofSize: 15)
    attrStr.enumerateAttribute(.font, in: NSRange(location: 0, length: attrStr.length), options: []) { value, subrange, pointeeStop in
        guard value == nil else { return }
        attrStr.addAttribute(.font, value: newFont, range: subrange)
    }