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的方法,直接屏蔽“打开链接”的系统动作:
- 创建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) } }
- 将项目中原有的UITextView替换为这个子类(代码创建或Storyboard中设置自定义类均可)。
额外验证项
- 确保
dataDetectorTypes已正确设置为.none:
textView.dataDetectorTypes = .none
- 你之前实现的
shouldInteractWith方法仅拦截点击链接的行为,不影响文本选择菜单,所以仍需搭配上述方案解决菜单问题。
内容的提问来源于stack exchange,提问作者user1749073
相关产品推荐
相关产品推荐

