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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With