swift - 是否有禁止粘贴到 UITextField 的首选技术?
问题描述
我已经阅读了针对不同版本的 Swift 提供的几种解决方案。
我看不到如何实现扩展——如果这甚至是最好的方法。
我确信这里有一个明显的方法,预计首先会被知道,但我没有看到它。我添加了这个扩展,我的文本字段都没有受到影响。
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)
}
}
推荐阅读
- sql - 根据列的值使用 SQL 求和
- javascript - 向 JS 多维对象添加新数据
- .net-core - 涉及代理时 Saml ReturnUrl 丢失
- moodle - 127.0.0.1 重定向你太多次 - Moodle 3.7
- command-line - 当我们使用命令行运行 Katalon 的测试时,有没有办法将结果消息发送到 slack?
- php - 在laravel中获取当前小时内的数据
- python - 如何跨多个文件创建不同的 Tkinter 帧?
- reactjs - 在子组件状态更改时,更新兄弟姐妹
- php - Foreach 仅针对条件中的一种情况的无效语句
- flutter - 使用自定义小部件时 Flutter UI 不会更新