I was tried to detecting backspace inside of UITextfieldDelegate. And found this answer. https://mcmap.net/q/162091/-detect-backspace-event-in-uitextfield
And It working correctly.
But I don't know what's going on inside of this function.
let char = string.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")
if isBackSpace == -92 {
print("Backspace was pressed")
return false
}
- I don't know why the result of cString of backspace is 0. I can debug on XCode. Please check the screenshot.
- I don't know why the strcmp about 0 for backspace(as far as I got this value on XCode debugger) and "\b" character returns -92
I knew the ascii code of backspace is "8" of type int so I thought above function would be like this code below.
// I thought this char would be "\b" of type char or 08 of type int
// but XCode give the value 0... I don't know why
let char = string.cString(using: String.Encoding.utf8)!
// as far as I know, strcmp returns positive value for equal values.
let isBackSpace = strcmp(char, "\\b")
// so I thought this would be
if isBackSpace > 0 {
print("Backspace was pressed")
return false // or true
}
Does anyone who can explain about this code step-by-step? Thank you.
ref :
https://linux.die.net/man/3/strcmp
https://theasciicode.com.ar/ascii-control-characters/backspace-ascii-code-8.html
Now I can understand why people use that code, and the code above is not correct.
Try to edit correctly by reffering to @Cristik's answer.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// backspace checking
if string == "" {
return true // or false
}