Change only fontsize of NSAttributedString

时光毁灭记忆、已成空白 提交于 2019-12-11 05:56:48

问题


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:


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?



来源:https://stackoverflow.com/questions/56102521/change-only-fontsize-of-nsattributedstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!