首页 > 解决方案 > 是否有禁止粘贴到 UITextField 的首选技术?

问题描述

我已经阅读了针对不同版本的 Swift 提供的几种解决方案。

我看不到如何实现扩展——如果这甚至是最好的方法。

我确信这里有一个明显的方法,预计首先会被知道,但我没有看到它。我添加了这个扩展,我的文本字段都没有受到影响。

extension UITextField {

    open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return action == #selector(UIResponderStandardEditActions.cut) || action == #selector(UIResponderStandardEditActions.copy)
    }
}

标签: swiftxcodepaste

解决方案


您不能使用扩展覆盖类方法。
来自文档“注意扩展可以向类型添加新功能,但它们不能覆盖现有功能。”

您需要的是子类 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)
    }
}

推荐阅读