I have a NSAttributedString that was loaded from a RTF file, so it already holds several font-attributes for different ranges. Now I want to adapt the font size to the screensize of the device, but when I add a whole new font attribute with a new size, the other fonts disappear.

Is there a way to change only the font size for the whole string?

1 Answers

3
rmaddy On Best Solutions

If you only want to change the size of any given font found in the attributed string then you can do:

let newStr = someAttributedString.mutableCopy() as! NSMutableAttributedString
newStr.beginEditing()
newStr.enumerateAttribute(.font, in: NSRange(location: 0, length: newStr.string.utf16.count)) { (value, range, stop) in
    if let oldFont = value as? UIFont {
        let newFont = oldFont.withSize(20) // whatever size you need
        newStr.addAttribute(.font, value: newFont, range: range)
    }
}
newStr.endEditing()

print(newStr)

This will keep all other attributes in place.

If you want to replace all fonts in a given attributed string with a single font of a given size but keep all other attributes such as bold and italic, see: NSAttributedString, change the font overall BUT keep all other attributes?