问题描述
我目前正在使用此提供的此扩展程序,将html转换为的UITextView 。一切都很完美,但由于某些奇怪的原因, NSFontAttributeName
在此过程中未应用于字符串。我在这里做错了吗? (或者我应该在重新使用归属的html解析字符串后应用 NSAttributedString
?如果是这样,是否可以将属性应用于 NSAttributeString
?)。
I'm currently using this extension provided by this answer to convert html to strings within a UITextView
. Everything works perfectly but for some strange reason the NSFontAttributeName
is not applied to the string during the process. Is there something I'm doing wrong here? (or should I apply the NSAttributedString
after reeving the attributed html parsed string? If so, is it possible to apply an attribute to an NSAttributeString
? ).
PS。使用 html2String
时字体大小不会改变,但html中的链接会被 UITextView
PS. Font size is not change when using html2String
but the links within the html is are longer recognized by the UITextView
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
推荐答案
我不确定为什么(可能是因为有一个范围)但是如果你首先创建一个NSMutableAttributedString然后添加UIFont属性它会起作用:
I'm not sure why (probably because of having a range) but it works if you first create an NSMutableAttributedString and then you add the UIFont attributes:
extension String {
var html2AttributedString: NSMutableAttributedString? {
guard
let data = dataUsingEncoding(NSUTF8StringEncoding)
else { return nil }
do {
let attrStr = try NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
attrStr.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(17.0)], range: NSRange(location: 0, length: attrStr.length))
return attrStr
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
这篇关于NSFontAttributeName未应用于NSAttributedString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!