I have a set up view that contains some textFields such as the users first and last name. I want to make sure that the user is not able to to enter in anything else except letters. After some research i found that the best method way to achieve this is with the textFieldShouldReplaceCharactersInRange delegate method. The code i have seems to work for only allowing them to enter in letters but it does not let me backspace. Ive read through the apple documentation for the method but im having a hard time grasping it. If it could be explained in a more noob friendly way that would be great and explain why backspacing in not being allowed would be great so i can truly understand. My code is below
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == firstNameTextField {
let allowedCharacter = NSCharacterSet.letters
let replacementTextHasRightCharacters = string.rangeOfCharacter(from: allowedCharacter as CharacterSet)
if replacementTextHasRightCharacters == nil {
return false
} else {
return true
}
}
return true
}
You do not need to use that function. Just create a target to run every time the textfield changes:
Then create the function that gets called: