问题描述
我已经阅读了几种针对不同版本的Swift的解决方案。
我看不到如何实现扩展-即使那是实现它的最佳方法。
我确定这里有一个显而易见的方法,应该首先知道,但是我没有看到它。我添加了此扩展名,但我的文本字段均不受影响。
extension UITextField {
open override func canPerformAction(_ action: Selector,withSender sender: Any?) -> Bool {
return action == #selector(UIResponderStandardEditActions.cut) || action == #selector(UIResponderStandardEditActions.copy)
}
}
解决方法
您不能使用扩展覆盖类方法。
docs中的注释:“扩展可以为类型添加新功能,但不能覆盖现有功能。”
您需要的是继承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)
}
}
,
Siwft 5
// class TextField: UITextField
extension UITextField {
open override func canPerformAction(_ action: Selector,withSender sender: Any?) -> Bool {
return action == #selector(UIResponderStandardEditActions.cut) || action == #selector(UIResponderStandardEditActions.copy)
}
}