About Me

My photo
Drum & Bass Producer, Software Developer, Love my Cats

iOS 10 Swift 3 How to limit input in a UITextField to Digits only (or any other set of characters) - Swift 3 Digits-only text field

If you want to create a UITextField that allows only inputting specific characters, simply set your viewcontroller as the text field's delegate and implement this delegate method:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string.characters.count > 0, !"1234567890".contains(string) {
            return false
// the rest of your logic goes here...


notice that here I'm allowing only any of these chars: "1234567890"
but your can change the string to any character set you want, for example "abcdefgh"(...) etc

notice the negative logic here: if this string is NOT contained in the character set you provided - then return false; else - do the rest of your logic..

[edit:] also, notice the first if:  string.characters.count > 0 which does not prevent deleting characters from the textfield (without this if-condition, you'll prevent your user from backspacing)

Also, it is best practice, of course, to choose the appropriate keyboard type in Interface Builder - based on what you want your user to input:
help your user