是否有禁止粘贴到 UITextField 的首选技术? [英] Is there a preferred technique to prohibit pasting into a UITextField?

查看:45
本文介绍了是否有禁止粘贴到 UITextField 的首选技术?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've read several offered solutions for different versions of Swift.

我看不到的是如何实现扩展——如果这是最好的方法的话.

What I cannot see is how to implement the extensions--if that's even the best way to go about it.

我确定这里有一个明显的方法,应该是最先知道的,但我没有看到.我已添加此扩展程序,但我的所有文本字段均不受影响.

I'm sure there is an obvious method here that was expected to be known first, but I'm not seeing it. I've added this extension and none of my text fields are affected.

extension UITextField {

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

推荐答案

您不能使用扩展覆盖类方法.
来自 docs 注意扩展可以向类型添加新功能,但它们不能覆盖现有功能."

You can not override a class method using an extension.
from the docs "NOTE Extensions can add new functionality to a type, but they cannot override existing functionality."

您需要的是继承 UITextField 并在那里覆盖您的方法:

What you need is to subclass UITextField and override your methods there:

仅禁用粘贴功能:

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)
    }
}


用法:


Usage:

let textField = TextField(frame: CGRect(x: 50, y: 120, width: 200, height: 50))
textField.borderStyle = .roundedRect
view.addSubview(textField)


只允许复制和剪切:


To allow only copy and cut:

class TextField: UITextField {
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        [#selector(UIResponderStandardEditActions.cut),
         #selector(UIResponderStandardEditActions.copy)].contains(action)
    }
}

这篇关于是否有禁止粘贴到 UITextField 的首选技术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆