gpt4 book ai didi

ios - UITextView中触发超链接文本点击和普通文本点击

转载 作者:行者123 更新时间:2023-11-28 23:23:32 26 4
gpt4 key购买 nike

您好,我正在尝试为超链接点击和 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 的委托(delegate)方法,并在 View 加载时执行 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
}
}

关于ios - UITextView中触发超链接文本点击和普通文本点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59244797/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com