如何检测锚标记链接单击从HTML字符串创建的NSAttributedString

时间:2018-06-21 12:50:17

标签: ios swift nsattributedstring

我正在使用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()
        }
    }
}

在这里,我想要一个回调方法来检测html字符串中的链接作为定位标记。 我如何在点击时获取事件,如何在事件回调中获取网址?

请帮助...

1 个答案:

答案 0 :(得分:1)

使用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()