web-dev-qa-db-ja.com

TextViewでHTMLテキストを表示する方法

HTMLを含む文字列があります。 HTMLをTextViewコントロールに表示したいと思います。私はいくつかのコードを見つけて試してみました:

def = "some html text"

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

オプションでエラーが発生します:

[文字列:文字列]は文字列に変換できません。

TextViewにHTMLを表示するのを手伝ってくれる人はいますか?

13
lascoff

これでうまくいきます。 NSAttributedStringコンストラクタがthrowsNSErrorオブジェクトになったことを思い出してください:

スウィフト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)
}
40
JAL

私がここで見つけたコードの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
0
Vitya Shurapov

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()
0
Scinfu