由于 rmaddy 的回答对我不起作用(f.fontDescriptor.withFace(font.fontName)
不保留粗体等特征),这是更新的 Swift 4 版本,还包括颜色更新:
extension NSMutableAttributedString {
func setFontFace(font: UIFont, color: UIColor? = nil) {
beginEditing()
self.enumerateAttribute(
.font,
in: NSRange(location: 0, length: self.length)
) { (value, range, stop) in
if let f = value as? UIFont,
let newFontDescriptor = f.fontDescriptor
.withFamily(font.familyName)
.withSymbolicTraits(f.fontDescriptor.symbolicTraits) {
let newFont = UIFont(
descriptor: newFontDescriptor,
size: font.pointSize
)
removeAttribute(.font, range: range)
addAttribute(.font, value: newFont, range: range)
if let color = color {
removeAttribute(
.foregroundColor,
range: range
)
addAttribute(
.foregroundColor,
value: color,
range: range
)
}
}
}
endEditing()
}
}
Or,如果您的混合属性不包括字体,
那么你不需要删除旧字体:
let myFont: UIFont = .systemFont(ofSize: UIFont.systemFontSize);
myAttributedText.addAttributes(
[NSAttributedString.Key.font: myFont],
range: NSRange(location: 0, length: myAttributedText.string.count));
Notes
问题在于f.fontDescriptor.withFace(font.fontName)
是它消除了像这样的象征性特征italic
, bold
or compressed
,因为由于某种原因它会覆盖那些具有该字体默认特征的字体。我完全不明白为什么会出现这种情况,这甚至可能是苹果的疏忽。或者它“不是一个错误,而是一个功能”,因为我们免费获得新字体的特性。
所以我们要做的是创建一个字体描述符,它具有原始字体的字体描述符的符号特征:.withSymbolicTraits(f.fontDescriptor.symbolicTraits)
。向 rmaddy 提供我迭代的初始代码。
我已经将其发送到生产应用程序中,我们通过以下方式解析 HTML 字符串NSAttributedString.DocumentType.html
然后通过上面的扩展更改字体和颜色。到目前为止没有问题。