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

Swift中如何禁用UITextView剪贴板的“打开链接”选项?

解决UITextView选中文本仍显示“打开链接”的问题

方案1:移除富文本的链接属性

如果你的UITextView使用了富文本,可能文本中被添加了NSAttributedString.Key.link属性,这会导致系统识别为链接并显示菜单选项。直接移除该属性即可:

if let attributedText = textView.attributedText {
    let mutableAttr = NSMutableAttributedString(attributedString: attributedText)
    mutableAttr.removeAttribute(.link, range: NSRange(location: 0, length: mutableAttr.length))
    textView.attributedText = mutableAttr
}

方案2:自定义UITextView拦截菜单动作

通过重写UITextView的方法,直接屏蔽“打开链接”的系统动作:

  1. 创建UITextView子类:
class NoLinkTextView: UITextView {
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        // 拦截打开链接的动作
        if action == #selector(UIResponderStandardEditActions.openURL(_:)) {
            return false
        }
        // 保留其他默认编辑功能
        return super.canPerformAction(action, withSender: sender)
    }
}
  1. 将项目中原有的UITextView替换为这个子类(代码创建或Storyboard中设置自定义类均可)。

额外验证项

  • 确保dataDetectorTypes已正确设置为.none:
textView.dataDetectorTypes = .none
  • 你之前实现的shouldInteractWith方法仅拦截点击链接的行为,不影响文本选择菜单,所以仍需搭配上述方案解决菜单问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 00:04:50