You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在UITextView中区分超链接文本点击与普通文本点击事件?

区分UITextView中超链接与普通文本的点击事件

要实现UITextView里超链接和普通文本触发不同点击事件,核心是避免手势冲突,并准确判断点击位置是否属于链接范围。你的现有代码里添加的UITapGestureRecognizer会拦截所有点击,导致链接的delegate方法无法正常工作,下面是修正后的实现方案:

解决方案步骤

  1. 移除全局点击手势:UITextView本身对链接有默认的交互支持,额外的全局手势会干扰这一逻辑。
  2. 通过Delegate处理链接点击:利用UITextViewDelegate的shouldInteractWith方法捕获链接点击,触发你的目标方法。
  3. 处理普通文本点击:重写touchesEnded方法,判断点击位置是否不属于任何链接范围,触发普通文本对应的方法。

修改后的完整代码

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var testTV: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let attributedHtmlText = """
        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(attributedHtmlText)
        testTV.isUserInteractionEnabled = true
        testTV.delegate = self
        // 确保textView可选择(默认是true,若手动设为false会导致链接无法交互)
        testTV.isSelectable = true
        // 禁止编辑,避免键盘弹出
        testTV.isEditable = false
    }
    
    // 普通文本点击触发的方法
    @objc func funcA() {
        print("普通文本被点击,触发funcA")
    }
    
    // 链接点击触发的方法
    @objc func funcB(url: URL) {
        print("链接被点击,触发funcB,URL:\(url)")
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        guard let touch = touches.first, let textView = touch.view as? UITextView else { return }
        
        // 获取点击位置在textView中的坐标
        let location = touch.location(in: textView)
        // 转换为文本范围对应的索引
        let characterIndex = textView.layoutManager.characterIndex(for: location, in: textView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
        
        // 判断该位置是否包含链接属性
        if let attributedText = textView.attributedText {
            if attributedText.attribute(.link, at: characterIndex, effectiveRange: nil) == nil {
                // 没有链接属性,触发普通文本点击方法
                funcA()
            }
        }
    }
}

extension ViewController: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        // 触发链接点击方法
        funcB(url: URL)
        // 返回false表示不打开系统默认的链接跳转
        return false
    }
}

关键说明

  • 手势冲突问题:你的原代码添加了全局点击手势,会优先于UITextView的链接交互被触发,导致链接点击无法被delegate捕获,所以必须移除这个手势。
  • 点击位置判断:在touchesEnded中,我们通过点击坐标转换为文本索引,再检查该位置是否有.link属性,以此区分普通文本和链接。
  • 属性设置:确保isSelectable = true,否则UITextView不会处理链接交互;isEditable = false可以避免用户编辑文本,同时不影响链接和普通文本的点击判断。

内容的提问来源于stack exchange,提问作者Ahil NS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:02:16