0

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

  • You're on the right track. it should be part of `UITextFieldDelegate` and specifically in this function: https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619599-textfield (Note: you would still be able to paste digits.) – Phillip Mills Aug 17 '20 at 18:58

1 Answers1

0

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))
    }
}
Li Jin
  • 1,879
  • 2
  • 16
  • 23