如何在 TextView 中显示 HTML 文本

How to display HTML text in TextView

我有一个包含 HTML 的字符串。我想在 TextView 控件中显示 HTML。我找到了一些代码并试了一下:

def = "some html text"

definition.attributedText = NSAttributedString(
  data: def.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
  options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
      documentAttributes: nil,
      error: nil)

在选项上我得到一个错误:

[String: String] is not convertible to string.

有人可以帮我在 TextView 中显示 HTML 吗?

这对我有用。请记住 NSAttributedString 构造函数现在 throws 一个 NSError 对象:

Swift 3:

do {
    let str = try NSAttributedString(data: def.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
} catch {
    print(error)
}

Swift 2.x:

do {
    let str = try NSAttributedString(data: def.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
} catch {
    print(error)
}

尝试SwiftSoup。这对我有用。

let html = "<html><head><title>First parse</title></head><body><p>Parsed HTML into a doc.</p></body></html>"
let doc: Document = try SwiftSoup.parse(html)
let text: String = try doc.text()

尝试使用我在此处找到的代码的 Swift3 版本:

https://github.com/codepath/objc_ios_guides/wiki/Generating-NSAttributedString-from-HTML

            func styledHTMLwithHTML(_ HTML: String) -> String {
                let style: String = "<meta charset=\"UTF-8\"><style> body { font-family: 'HelveticaNeue'; font-size: 20px; } b {font-family: 'MarkerFelt-Wide'; }</style>"
                return "\(style)\(HTML)"
            }

            func attributedString(withHTML HTML: String) -> NSAttributedString {
                let options: [AnyHashable: Any] = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
                return try! NSAttributedString(data: HTML.data(using: String.Encoding.utf8)!, options: options as! [String : Any], documentAttributes: nil)
            }

            // This is a string that you might find in your model
            var html: String = "This is <b>bold</b>"

            // Apply some inline CSS
            var styledHtml: String = styledHTMLwithHTML(html)

            // Generate an attributed string from the HTML
            var attributedText: NSAttributedString = attributedString(withHTML: styledHtml)

            // Set the attributedText property of the UILabel
            label.attributedText = attributedText