在UITextView中显示HTML字符串

时间:2014-12-20 02:08:48

标签: ios swift uitextview nsattributedstring

我正在尝试在UITextView中显示HTML字符串。这是关键路线:

self.postPage.attributedText = NSAttributedString(string: myHTMLString)

我看到的问题是<div>代码<img>代码仍然显示...我有什么问题吗?

3 个答案:

答案 0 :(得分:3)

extension String {
    var html2String:String {
        return NSAttributedString(data: dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil, error: nil)!.string
    }
}

"<div>Testing<br></div><img src=\"http://....\">".html2String  // "Testing\n"

答案 1 :(得分:3)

如果您使用Xcode 7.0.1,则需要添加try!

extension String {
    var html2String:String {
        return try! NSAttributedString(data: dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil).string
    }
}

答案 2 :(得分:0)

此功能会将所有HTML标记转换为NSAttributedString

extension String{    
    func convertHtml() -> NSAttributedString{
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do{
            return try NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
        }catch{
            return NSAttributedString()
        }
    }
}

用法如下:

yourTextView.attributedText = yourHtmlString.convertHtml()