如何检测从 html 字符串创建的 NSAttributedString 中的锚标记链接点击

Bra*_*oni 3 nsattributedstring ios swift

我正在使用 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>"
Run Code Online (Sandbox Code Playgroud)

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

someLabel.attributedText = htmlString.htmlToAttributedString
Run Code Online (Sandbox Code Playgroud)

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

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

请帮忙...

Gov*_*wat 5

使用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]
Run Code Online (Sandbox Code Playgroud)

UITextViewDelegate方法shouldInteractWithURL

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

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

那么你可以像这样使用它。

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()
Run Code Online (Sandbox Code Playgroud)