我想在iOS应用中显示以下html文字
<p><span style="color: #000000;">Experience royalty in all its splendor</span><br /><span style="color: #000000;"> An address that is a possession of pride</span></p>
我尝试使用NSAttributedString并在html字符串中添加字体,但无效
let st:String = pjt.value(forKey: "description") as! String // Original content from API - "<p><span style="color: #000000;">Experience royalty in all its splendor</span><br /><span style="color: #000000;"> An address that is a possession of pride</span></p><........"
let desc:Data = st.data(using: String.Encoding.utf8, allowLossyConversion: true)!
//st.data(using: String.Encoding.utf16)!
do {
let attrStr = try NSAttributedString(data: desc, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes: nil)
print("Attr STr \(attrStr)")
self.textView.attributedText = attrStr;
}
它也无法在self.webView.loadHTMLString(st, baseURL: nil)
更新
Textview或webview或label all显示相同的普通html字符串<p><span style="color: #000000;">Experience royalty in all its splendor</span><br /><span style="color: #000000;"> An address that is a possession of pride</span></p>
有任何帮助吗?
注意:Swift 3
谢谢!
答案 0 :(得分:2)
你的字符串是
"<p><span style="color: #000000;">Experience royalty in all its splendor</span><br /><span style="color: #000000;"> An address that is a possession of pride</span></p>"
将所有HTML标记编码为HTML实体。该字符串必须转换为
<p><span style="color: #000000;">Experience royalty in all its splendor</span><br /><span style="color: #000000;"> An address that is a possession of pride</span></p>
之前 将其传递给属性字符串。例如,这可以
使用How do I decode HTML entities in swift?中的stringByDecodingHTMLEntities
方法完成:
let st = (pjt.value(forKey: "description") as! String).stringByDecodingHTMLEntities
(与您当前的问题无关:强制演员as! String
如果值不存在或者不是字符串,则可能在运行时崩溃。
您应该使用可选绑定。)