Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

swift - Is there a preferred technique to prohibit pasting into a UITextField?

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)
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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."

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

To only disable paste functionality:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...