来自 HTML 的带有超链接的 NSAttributedString

NSAttributedString from HTML with Hyperlinks

我正在尝试使用 NSAttributedString 将包含 hyperlinks 的大 HTML 字符串渲染到 UITextView 中。除 hyperlinks 外,一切正常,它们实际上并没有打开 link。

例如,这是我的 html 字符串的虚拟版本:

let htmlString = "<html><p>If you would like to contact someone, you can email 
them at <a class=rvts10 href=\"mailto:some@one.com\">some@one.com</a></p></html>"

我有一个名为 convertHTML() 的函数,它使用 html 文档类型选项将字符串转换为 NSAttributedString,我用它来分配给 UITextView 的属性文本:

textView.attributedText = htmlString.convertHTML()

TextField 是 selectable 但不是 editable。加载页面后,您可以看到 hyperlink 样式(蓝色文本)和所有内容,但无法点击 link 并打开邮件应用程序。

我假设我需要将 "mailto:..." 更改为 iOS 可以识别的其他内容,但我不知道需要做什么才能使 link link能。


这是我的html方法:

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

我认为您的 convertHTML() 方法有误,请检查此

 let htmlString = "<html><p>If you would like to contact someone, you can email them at <a class=rvts10 href=\"mailto:some@one.com\">some@one.com</a></p></html>"

            // you have to convert string to data
            let data = Data(htmlString.utf8)
            // then convert data to NSAttributedString with NSAttributedString.DocumentType.htm
            if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
                self.textView.attributedText = attributedString
            }

我使用这个扩展程序:

import Foundation

    extension NSAttributedString {

        convenience init(htmlString html: String) throws {
            try self.init(data: Data(html.utf8), options: [
                .documentType: NSAttributedString.DocumentType.html,
                .characterEncoding: String.Encoding.utf8.rawValue
                ], documentAttributes: nil)
        }

    }

实现后你可以像这样使用它:

contentTextField.attributedText = try? NSAttributedString(htmlString: aHTMLString)