【发布时间】:2016-04-05 13:13:59
【问题描述】:
我目前正在使用此answer 提供的此扩展程序将html 转换为UITextView 中的字符串。一切正常,但由于某些奇怪的原因,NSFontAttributeName 在此过程中未应用于字符串。我在这里做错了什么吗? (或者我应该在查看属性化的 html 解析字符串后应用 NSAttributedString 吗?如果是这样,是否可以将属性应用到 NSAttributeString?)。
PS。使用html2String 时字体大小没有变化,但UITextView 可以识别html 中的链接
extension String {
var html2AttributedString: NSAttributedString? {
guard
let data = dataUsingEncoding(NSUTF8StringEncoding)
else { return nil }
do {
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding, NSFontAttributeName : UIFont.systemFontOfSize(17.0)], documentAttributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
cell.desc.attributedText = apiData[currentIndex].description!.html2AttributedString //Font attribute not recognized
cell.desc.text = apiData[currentIndex].description!.html2String //Font recognized by links no longer recognized
【问题讨论】:
-
这是正常行为。
NSFontAttributeName不是initWithData:options:documentsAttributes:error:中options参数的允许键。您必须在之后重写字体效果。因此,要么通过将 HTML 添加到原始字符串中来应用它,要么在之后应用它(这样可能会删除粗体/斜体效果)。 -
@Larme 感谢您提供这些详细信息,我不知道此方法中忽略了此属性。如果他们决定像这样转换,我将把答案留给 OP。
标签: ios swift nsattributedstring