You need to enable JavaScript to run this app. Swift实现UITextView中URL可点击同时支持文本编辑的问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Swift实现UITextView中URL可点击同时支持文本编辑的问题求助

UITextView同时支持链接点击与编辑的实现方案(适配苹果备忘录效果)

系统原生UITextView默认在isEditable = true状态下不会自动响应链接点击事件,我们可以通过自定义手势检测点击位置是否属于链接范围,在不切换编辑状态的前提下实现需求。

完整实现步骤

  1. 基础配置:全程保持编辑状态开启,无需来回切换isEditable属性
// UITextView初始化配置
txtVw.isEditable = true
txtVw.isSelectable = true
txtVw.dataDetectorTypes = .link
txtVw.linkTextAttributes = [
    .foregroundColor: UIColor.blue, 
    .underlineStyle: NSUnderlineStyle.single.rawValue
]
txtVw.delegate = self

// 添加自定义点击手势
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTextViewTap(_:)))
tapGesture.delegate = self
tapGesture.cancelsTouchesInView = false
txtVw.addGestureRecognizer(tapGesture)
  1. 实现链接点击检测逻辑
@objc private func handleTextViewTap(_ gesture: UITapGestureRecognizer) {
    guard let textView = gesture.view as? UITextView else { return }
    let location = gesture.location(in: textView)
    
    // 获取点击位置对应的字符索引(兼容全iOS版本)
    let layoutManager = textView.layoutManager
    let textContainer = textView.textContainer
    let textBounding = layoutManager.usedRect(for: textContainer)
    guard location.y >= textBounding.minY, location.y <= textBounding.maxY else { return }
    
    let glyphIndex = layoutManager.glyphIndex(for: location, in: textContainer)
    let charIndex = layoutManager.characterIndexForGlyph(at: glyphIndex)
    
    // 校验是否点击在链接区域
    guard charIndex < textView.attributedText.length,
          let linkUrl = textView.attributedText.attribute(.link, at: charIndex, effectiveRange: nil) as? URL else {
        // 非链接区域走原生编辑逻辑,无需额外处理
        return
    }
    
    // 触发链接跳转
    UIApplication.shared.open(linkUrl)
}
  1. 实现手势代理,避免和原生编辑手势冲突
extension 你的控制器类名: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        // 允许多手势同时识别,保证选中、编辑、链接点击交互无冲突
        return true
    }
}

效果说明

该方案实现的交互和苹果自带备忘录完全一致:

  • 点击链接区域直接跳转对应网页
  • 点击非链接区域直接激活编辑状态
  • 长按可选中文字、触发链接的预览/复制等系统菜单
  • 支持自动识别输入过程中新增的链接,无需手动刷新属性

内容的提问来源于stack exchange,提问作者Talat Baig

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 15:45:03