Learn Courses My Dashboard

shouldChangeCharactersIn and the Delete key

Hi all,
I have a textfield that I want to limit to letter input only. The code below works for that, but the problem is it also excludes the delete key, which means the user cannot correct any spelling errors. I’m guessing that the delete key is itself a character, but searching has so far proved fruitless. Does anyone know what characterSet the delete key belongs to and/or what it looks like as a character?

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) → Bool {
return string.rangeOfCharacter(from: CharacterSet.letters) != nil
}

Per the docs for textField(_:shouldChangeCharactersIn:replacementString:): “When the user deletes one or more characters, the replacement string is empty.”

So try this in your return statement:

return string.isEmpty || string.rangeOfCharacter(from: CharacterSet.letters) != nil

Thanks very much for that. I need to get into the habit of delving into the docs. My first instinct is usually to google.