Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...