假设我有一个NSMutableAttributedString.
该字符串具有各种格式:
这是一个例子:
This string is hell to change in iOS,it really sucks.
但是,字体本身不是您想要的字体.
我想要:
对于每个角色,将该角色更改为特定字体(例如,Avenir)
但,
对于每个角色,保留以前在该角色上使用的其他属性(粗体,斜体,颜色等).
你到底怎么这样做?
注意:
如果您在整个范围内轻松添加属性“Avenir”:它只是删除所有其他属性范围,您将丢失所有格式.不幸的是,属性实际上并不是“附加的”.
解决方法
由于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() } }
笔记
f.fontDescriptor.withFace(font.fontName)的问题在于它删除了斜体,粗体或压缩等符号特征,因为它会因某种原因覆盖具有该字体的默认特征的特征.为什么这一点完全无法实现,甚至可能是苹果公司的疏忽;或者它“不是一个错误,而是一个功能”,因为我们免费获得新字体的特征.
所以我们要做的是创建一个字体描述符,它具有原始字体的字体描述符的符号特征:.withSymbolicTraits(f.fontDescriptor.symbolicTraits).转发到rmaddy我的迭代的初始代码.
我已经在生产应用程序中发送了这个,我们通过NSAttributedString.DocumentType.html解析HTML字符串,然后通过上面的扩展名更改字体和颜色.到目前为止没问题.