Cannot backspace after implementing textFieldShouldReplaceCharactersInRange

83 views Asked by At

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
}
1

There are 1 answers

0
Nathan On

You do not need to use that function. Just create a target to run every time the textfield changes:

textField.addTarget(self, action: #selector(YourViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)

Then create the function that gets called:

func textFieldDidChange(textField: UITextField) {
     let letters = CharacterSet.letters

     for letter in textField.text!.unicodeScalars {
        if letters.contains(letter) {
           // is a letter
        } else {
           // not a letter
        }
     }
}