Swift 是否有禁止粘贴到UITextField的首选技术?
我已经阅读了为不同版本的Swift提供的几种解决方案 我看不到的是如何实现扩展——如果这是最好的方法的话 我确信这里有一个显而易见的方法,它应该首先被知道,但我没有看到它。我已经添加了这个扩展名,我的所有文本字段都不受影响Swift 是否有禁止粘贴到UITextField的首选技术?,swift,xcode,paste,Swift,Xcode,Paste,我已经阅读了为不同版本的Swift提供的几种解决方案 我看不到的是如何实现扩展——如果这是最好的方法的话 我确信这里有一个显而易见的方法,它应该首先被知道,但我没有看到它。我已经添加了这个扩展名,我的所有文本字段都不受影响 extension UITextField { open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { return
extension UITextField {
open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return action == #selector(UIResponderStandardEditActions.cut) || action == #selector(UIResponderStandardEditActions.copy)
}
}
不能使用扩展重写类方法。
“注释扩展可以向类型添加新功能,但不能覆盖现有功能。” 您需要的是将UITextField子类化并重写其中的方法: 要仅禁用粘贴功能,请执行以下操作:
class TextField: UITextField {
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(UIResponderStandardEditActions.paste) {
return false
}
return super.canPerformAction(action, withSender: sender)
}
}
用法:
let textField = TextField(frame: CGRect(x: 50, y: 120, width: 200, height: 50))
textField.borderStyle = .roundedRect
view.addSubview(textField)
要仅允许复制和剪切,请执行以下操作:
class TextField: UITextField {
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
[#selector(UIResponderStandardEditActions.cut),
#selector(UIResponderStandardEditActions.copy)].contains(action)
}
}
小五
// class TextField: UITextField
extension UITextField {
open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return action == #selector(UIResponderStandardEditActions.cut) || action == #selector(UIResponderStandardEditActions.copy)
}
}
你在哪里看到这个“解决方案”贴出来的?请提供链接。“扩展可以向类型添加新功能,但不能覆盖现有功能。”将永远不会调用您的canPerformAction方法