来自带有超链接的 HTML 的 NSAttributedString

6 html hyperlink uitextview nsattributedstring swift

我正在尝试使用 NSAttributedString 将包含超链接的大型 HTML 字符串渲染到 UITextView 中。除了超链接之外,一切都工作正常,它们实际上并没有打开链接。

例如,这是我的 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>"
Run Code Online (Sandbox Code Playgroud)

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

textView.attributedText = htmlString.convertHTML()
Run Code Online (Sandbox Code Playgroud)

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

我认为我需要将“mailto:...”更改为 iOS 可以识别的其他内容,但我只是不知道需要做什么才能允许此链接可链接。


这是我的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()
    }
}
Run Code Online (Sandbox Code Playgroud)

Abd*_*ish 0

我认为您的 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
            }
Run Code Online (Sandbox Code Playgroud)