UITextView重写canPerformAction时无法识别replace(_:)选择器的问题
解决UITextView编辑菜单中replace选择器的检查问题
你遇到的问题是因为replace(_:)并非UITextView公开暴露的方法,所以直接用#selector(replace(_:))会找不到符号。虽然通过action.description == "replace:"能临时解决,但这种依赖字符串描述的方式确实不够健壮——苹果可能在未来版本中修改选择器的字符串表现,或者不同本地化环境下出现差异。
更可靠的做法是使用NSSelectorFromString("replace:")来获取该选择器,这是系统提供的安全方式,能直接匹配系统内部使用的选择器。
修改后的代码如下:
class NewTextView: UITextView { override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { let allowedActions: [Selector] = [ #selector(paste(_:)), #selector(copy(_:)), #selector(cut(_:)), #selector(select(_:)), #selector(selectAll(_:)), NSSelectorFromString("replace:") ] if allowedActions.contains(action) { return super.canPerformAction(action, withSender: sender) } return false } }
这种方式既避免了符号找不到的问题,又比硬编码字符串描述更稳定,能确保在不同iOS版本中都能正确识别replace操作。
内容的提问来源于stack exchange,提问作者Sundara Aadithyan
相关产品推荐
相关产品推荐

