本文介绍了无法将NSAttributedString.DocumentAttributeKey类型的值转换为.DocumentReadingOptionKey的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在互联网上找到了这个字符串扩展,允许我将html代码转换为属性字符串:
I found this string extension somewhere on the internet that allows me to turn html code into an attributed string:
func html2AttributedString() -> NSAttributedString {
return try! NSAttributedString(data: self.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
}
它在Swift 3中运行良好,但是对于Swift 4,Xcode抱怨:
It worked fine in Swift 3, but with Swift 4, Xcode complains:
如何做我解决了这个问题?
How do I fix this?
推荐答案
你需要传递一个可用的NSAttributedString 选项:
You need to pass one of the available NSAttributedString DocumentType options:
static let html: NSAttributedString.DocumentType
static let plain: NSAttributedString.DocumentType
static let rtf: NSAttributedString.DocumentType
static let rtfd: NSAttributedString.DocumentType
在这种情况下,您需要传递第一个(html) NSAttributedString.DocumentType.html
所以扩展到Swift 4应该如下所示:
So the extension updated to Swift 4 should look like this:
extension String {
var html2AttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: Data(utf8),
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
} catch {
print("error: ", error)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
这篇关于无法将NSAttributedString.DocumentAttributeKey类型的值转换为.DocumentReadingOptionKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!