我有一个通过 NSAttributedString
函数显示 HTML 的标签。
问题是我想给它添加自定义字体,但它没有添加字体。
我做错了什么?
这是我的代码:
extension String {
func convertHtml() -> NSAttributedString {
let titleAttributes = [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline), NSAttributedStringKey.foregroundColor: UIColor.black]
guard let data = data(using: .utf8) else { return NSAttributedString() }
do{
return try NSAttributedString(data: data,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
}catch{
return NSAttributedString.init(string: self, attributes: titleAttributes)
}
}
}
最佳答案
如果您希望从生成的 HTML 中替换所有字体设置,您需要在从 HTML 字符串创建属性字符串后应用您的 titleAttributes
。
extension String {
func convertHtml() -> NSAttributedString {
let titleAttributes = [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline), NSAttributedStringKey.foregroundColor: UIColor.black]
guard let data = data(using: .utf8) else { return NSAttributedString() }
do{
let res = try NSAttributedString(data: data,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
let mutable = res.mutableCopy() as! NSMutableAttributedString
mutable.addAttributes(titleAttributes, range: NSRange(location: 0, length: res.length))
return mutable
}catch{
return NSAttributedString.init(string: self, attributes: titleAttributes)
}
}
}
关于ios - NSAttributedString 不会显示正确的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48532626/