在 UITextView 中触发超 link 文本点击和普通文本点击

Trigger hyper link text click and and normal text click in UITextView

您好,我正在尝试为超 link 点击和 UITextView

中的普通文本点击触发单独的点击事件

如何在 UITextView

中分离超 link 文本点击和普通文本点击

希望你能理解我的问题。

这是我试过的。

     override func viewDidLoad() {
        super.viewDidLoad()
        let atributedHtmlText = """
            Hey I dont have hyper link text so trigger func A(). Click <a href="http://www.google.com">I have hyper link so trigger func b here</a> for more information.
            """
        testTV.setAttributedHtmlText(atributedHtmlText)

        let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapFunction))
        testTV.isUserInteractionEnabled = true
        testTV.addGestureRecognizer(tap)
        testTV.delegate = self
     }

     @objc func tapFunction(sender:UITapGestureRecognizer) {
        print("tap working")
     }

     extension ViewController: UITextViewDelegate {
        func textView(_ textView: UITextView, shouldInteractWith URL: URL,
                  in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
          print("URL Text Tapped ", URL)
          return false
    }
}

定义一个属性字符串,然后通过定义要点击打开 link 的范围来为其添加属性。并且不要忘记添加 textView 的委托方法,并在视图中执行 YourTextView.delegate = self 加载。

    class ViewController: UIViewController, UITextViewDelegate {
    @IBOutlet var textView: UITextView!

    override func viewDidLoad() {
        textView.delegate = self.
        let attributedString = NSMutableAttributedString(string: "want to search something on Google! Click Here")
        attributedString.addAttribute(.link, value: "www.google.com", range: NSRange(location: 36, length: 10))

        textView.attributedText = attributedString
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        UIApplication.shared.open(URL)
        return false
    }
}

一个可能的解决方案是在没有 link 属性的地方添加一个 "fake URL"(就像“内部 URL 方案看起来很相似):

attributedText.enumerateAttribute(.link, in: NSRange(location: 0, length: attributedText.length), options: []) { (attribute, range, pointee) in
    //If there is no URL => Set our custom one
    if attribute == nil {
        attributedText.addAttribute(.link, value: "com.myapp.custom", range: range)
    }
}

并在此委托方法中,检查 URL 的值。

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    print("url: \(URL)")
    if url == ... {} else { ... }
    return false
}