嗨,我正在尝试为UITextView中的超链接单击和普通文本单击触发单独的单击事件。
如何在UITextView中分隔超链接文本单击和普通文本单击。希望你理解我的问题。
这是我尝试过的。
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
}
}
定义属性字符串,然后通过定义要点按以打开链接的范围来向其中添加属性。并且不要忘记添加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
}
}