user14108256
user14108256

Reputation:

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

Upvotes: 1

Views: 1197

Answers (2)

Mithra Singam
Mithra Singam

Reputation: 2091

Siwft 5

 // class TextField: UITextField
extension UITextField {

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

Upvotes: 0

Leo Dabus
Leo Dabus

Reputation: 236360

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

Upvotes: 1

Related Questions