如何检测锚标记 link 单击从 html 字符串创建的 NSAttributedString

How to detect anchor tag link click in NSAttributedString created from html string

我正在使用 html:

创建 NSAttributedString
let htmlString = "<body style='padding-left:50px'><h1>Hello World</h1><div><a href=https://apple.com/offer/samsung-faq/>Click Here</a></div><p>This is a sample text</p><pre>This is also sample pre text</pre></body>"

这里我使用扩展方法将它设置为 UILabel

someLabel.attributedText = htmlString.htmlToAttributedString

NSAttributedString 扩展:

extension String {
    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
            return try NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType:  NSAttributedString.DocumentType.html], documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }
}

这里我想要一个回调方法来检测 link 在 html 字符串中作为锚标记。 我将如何获得点击事件以及如何在该事件回调中获得 url?

请帮忙...

使用 UITextView 而不是 UILabel,它有一个 属性 可以将您的文本转换为超链接。

您必须UIViewController确认UITextViewDelegate协议并实施textView(_:shouldInteractWith:in:interaction:。您的标准 UITextView 设置应如下所示,不要忘记 delegatedataDetectorTypes

@IBOutlet weak var txtView: UITextView!
// make IBOutlet of UITextView

txtTest.delegate = self
txtTest.isUserInteractionEnabled = true // default: true
txtTest.isEditable = false // default: true
txtTest.isSelectable = true // default: true
txtTest.dataDetectorTypes = [.link]

UITextViewDelegate方法shouldInteractWithURL:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    print("Link Selected!")
    return true
}

HTMLNSAttributedString 分机:

extension String{
    func convertHtml() -> NSAttributedString{
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do{
            return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
        }catch{
            return NSAttributedString()
        }
    }
}

那你就可以这么用了

let htmlString = "<body style='padding-left:50px'><h1>Hello World</h1><div><a href=https://apple.com/offer/samsung-faq/>Click Here</a></div><p>This is a sample text</p><pre>This is also sample pre text</pre></body>"

txtTest.attributedText = htmlString.convertHtml()