仅更改NSAttributedString的字体大小 [英] Change only fontsize of NSAttributedString

查看:226
本文介绍了仅更改NSAttributedString的字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从RTF文件加载的NSAttributedString,所以它已经包含了不同范围的几个字体属性. 现在,我想使字体大小适应设备的屏幕大小,但是当我添加一个具有新大小的全新字体属性时,其他字体就会消失.

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.

是否可以更改整个字符串的 only 字体大小?

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

推荐答案

如果只想更改在属性字符串中找到的任何给定字体的大小,则可以执行以下操作:

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.

如果要将给定属性字符串中的所有字体替换为给定大小的单个字体,但保留所有其他属性(如粗体和斜体),请参见: NSAttributedString,更改字体整体,但保留所有其他属性吗?

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?

这篇关于仅更改NSAttributedString的字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆