在文本视图中有效地显示 html 内容



我正在使用这种方式,它工作正常,但由于我在研究时使用NSHTMLTextDocumentType而回退缓慢

do {
    let attributedOptions:[String: Any] = [
        NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
        NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue]
    let date = html.data(using: String.Encoding.utf8, allowLossyConversion: true)!
    return try NSAttributedString(data: data, options: attributedOptions , documentAttributes: nil)
} catch let error as NSError {
    print("htmo2String (error)")
}

任何想法如何更快地做到这一点或其他有效的方法!

也许您可以在队列上执行解析代码...

func parse(_ html: String, completionHandler: @escaping (_ attributedText: NSAttributedString?) -> (Void)) -> Void
{
    let htmlData = text.data(using: String.Encoding.utf8, allowLossyConversion: false)
    let options: [String: AnyObject] = [
        NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType as AnyObject
    ]
    completionHandler(try? NSAttributedString(data: htmlData!, options: options, documentAttributes: nil))
}

现在调用函数并等待响应...

let queue: DispatchQueue = DispatchQueue(label: "com.yourcompany.Process./html_converter")
queue.async
{
    parse("<p>¡Hola mundo</p>", completionHandler: { (attributtedString: NSAttributedString?) -> (Void) in 
        if let attributtedString = attributtedString
        {
            DispatchQueue.main.async
            {
                print("str:: (attributtedString)")
            }
        }
    })
}

您是否尝试过使用 UIWebView 来呈现 HTML 内容?

您可以根据需要显示字符串或 URL 中的 HTML。

下面是一个从字符串显示 HTML 的示例:

string sHTMLContent = "<html><head><body><p>Hello World</p></body></head></html>";
m_WebView.LoadHtmlString(sHTMLContent , null);

然后,可以将 Web 视图的大小设置为与具有约束的文本视图相等。如果需要,Web 视图将自动滚动。

最终字符串扩展,以异步@Adolfo有效地显示html字符串

具有更改字体和颜色^_^的能力

extension String {
func html2StringAsync(_ fontSize: CGFloat? = nil, color: UIColor? = nil, completionBlock:@escaping (NSAttributedString) ->()) {
    let fontSize = fontSize ?? 10
    let fontColor = color ?? UIColor.black
    let font = "Avenir !important"
    let html = "<div style="font-family:(font); font-size:(fontSize)pt; color:(fontColor.hexString);">" + self + "</div>"
    if let data = html.data(using: String.Encoding.utf8, allowLossyConversion: true){
        DispatchQueue.main.async {
            do {
                let attributedOptions:[String: Any] = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                       NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue]
                let attrStr = try NSAttributedString(data: data, options: attributedOptions , documentAttributes: nil)
                completionBlock(attrStr)
            } catch let error as NSError {
                print("htmo2String (error)")
            }
        }
    }else{
        completionBlock(NSAttributedString(string: self))
    }
}
}

最新更新