Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextfield keyboard with only alphabet, no numbers, no caps, no spacebar?

Tags:

xcode

ios

swift

I want the keyboard for the UITextfield to only have a-z, no numbers, no special characters (!@$!@$@!#), and no caps. Basicly I am going for a keyboard with only the alphabet.

I was able to disable the space already. Anyone know how to disable numbers, special characters, and caps? A solution for any of these would be great.

Is the best solution to do the below for all the characters but I dont want?

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if (string == " ") {
        return false
    }

    if (string == "1") {
        return false
    }

    return true
}
like image 971
gooberboobbutt Avatar asked Jul 17 '15 16:07

gooberboobbutt


3 Answers

An easiet way would be:

if let range = string.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet())
    return true
}
else {
    return false
}
like image 133
Lennet Avatar answered Nov 20 '22 15:11

Lennet


Update for those who wants to Allow Space, Caps & Backspace Only

Swift 4.x, Swift 5.x & up

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if range.location == 0 && string == " " { // prevent space on first character
        return false
    }

    if textField.text?.last == " " && string == " " { // allowed only single space
        return false
    }

    if string == " " { return true } // now allowing space between name

    if string.rangeOfCharacter(from: CharacterSet.letters.inverted) != nil {
        return false
    }

    return true
}
like image 9
iAj Avatar answered Nov 20 '22 16:11

iAj


Swift 3 solution

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

     let characterSet = CharacterSet.letters

     if string.rangeOfCharacter(from: characterSet.inverted) != nil {
         return false      
     }
     return true
}
like image 6
Santiago Carmona González Avatar answered Nov 20 '22 15:11

Santiago Carmona González