2017-08-06 46 views
0

我想顯示在iOS應用下面的HTML文本如何斯威夫特解碼HTML格式文本3

<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 - "&lt;p&gt;&lt;span style=&quot;color: #000000;&quot;&gt;Experience royalty in all its splendor&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: #000000;&quot;&gt; An address that is a possession of pride&lt;/span&gt;&lt;/p&gt;&lt;........" 

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或標籤全部顯示相同的純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>

任何幫助嗎?

注意:斯威夫特3個

謝謝!

+0

顯示一些額外的代碼 –

+0

您'讓ST:String'錯誤檢查一次更新之前的字符串 –

+0

@ Anbu.Karthik好 – Gopik

回答

2

你的字符串是

"&lt;p&gt;&lt;span style=&quot;color: #000000;&quot;&gt;Experience royalty in all its splendor&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: #000000;&quot;&gt; An address that is a possession of pride&lt;/span&gt;&lt;/p&gt;" 

編碼爲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> 

之前將它傳遞給屬性串。例如,這可以 使用stringByDecodingHTMLEntities方法來完成從How do I decode HTML entities in swift?

let st = (pjt.value(forKey: "description") as! String).stringByDecodingHTMLEntities 

(無關到當前的問題:強制投as! String 可以在運行時崩潰,如果該值不存在或不是一個字符串 。您應該使用可選的,而不是綁定)

+0

謝謝馬丁!!!!!有用。 – Gopik