Search code examples
swiftextension-methodspaste

Preventing pasting into a textField in swift 5


I've got this extension in my code to limit the length of a textField I've got.

I'm trying to get the thing to prohibit pasting--since I'm using the numbered to enter the 3-digit value.

I just can't seem to get these code snippets put to the right place.

Will this work if I put it inside the extension Viewcontroller:UITextFieldDelegate that I've got down at the bottom of my code block?

I'm early in the learning process and sometimes where to drop things don't go so well. Thanks in advance.

enter image description here


Solution

  • This code will make the textfield to accept only numbers.

     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let invalidCharacters = CharacterSet(charactersIn: "0123456789").inverted
        return string.rangeOfCharacter(from: invalidCharacters) == nil
    }
    

    And This code will prevent paste. This enables only cut and copy functions.

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