gpt4 book ai didi

swift - NSAttributedString,更改字体总体,但保留所有其他属性吗?

转载 作者:行者123 更新时间:2023-11-29 05:46:54 25 4
gpt4 key购买 nike

说我有一个NSMutableAttributedString

在整个字符串中,字符串具有多种格式组合:

这是一个例子:


  这个字符串在iOS中很难改变,真的很烂。


但是,字体本身不是您想要的字体。

我想要:

对于每个字符,将该字符更改为特定字体(例如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)的问题在于它会删除诸如 italicboldcompressed之类的符号特征,因为出于某种原因它将覆盖那些具有该字体外观默认特征的特征。为什么这是如此让我难以理解,甚至可能是苹果的疏忽。或“不是错误,而是功能”,因为我们免费获得了新字体的特征。

因此,我们要做的是创建一个字体描述符,该描述符具有原始字体的字体描述符 .withSymbolicTraits(f.fontDescriptor.symbolicTraits)的符号特征。为rmaddy支持我迭代的初始代码。

我已经在生产应用程序中交付了此代码,我们在其中通过 NSAttributedString.DocumentType.html解析HTML字符串,然后通过上述扩展名更改字体和颜色。到目前为止没有问题。

关于swift - NSAttributedString,更改字体总体,但保留所有其他属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56057068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com