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
}
When you tap the backspace check for backspace code and return false if rangeOfCharacter for your regular expression is nil else return true.
Try this:
let char = text.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92) {
}else if text.range(of: kRangeWithoutSpace, options:.regularExpression) == nil {
return false
}