Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow Backspace with character set

I am having trouble deleting in my text field. So I have a text field for a person name only allowing letters. But when I hit the delete or backspace it doesn't seem to work. This is what my code looks like.

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let set = CharacterSet.letter
    return (string.rangeOfCharacter(from: set) != nil)
}

I am not sure why the backspace/delete is not working.

like image 424
Luis F Ramirez Avatar asked Mar 04 '23 15:03

Luis F Ramirez


1 Answers

When the user taps the backspace, string will be the empty string. So rangeOfCharacter will be nil so your code returns false preventing the backspace from working.

Try this:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return string.isEmpty || string.rangeOfCharacter(from: CharacterSet.letter) != nil
}
like image 98
rmaddy Avatar answered Mar 15 '23 01:03

rmaddy