我试图检测 UITextfieldDelegate 内部的退格键。
并找到了这个答案。https://stackoverflow.com/a/49294870/911528
并且它工作正常。
但我不知道这个函数内部发生了什么。
let char = string.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")
if isBackSpace == -92 {
print("Backspace was pressed")
return false
}
- 我不知道为什么退格键的cString结果是0。
我可以在 XCode 上进行调试。请检查屏幕截图。
- 我不知道为什么 strcmp 的退格键为 0(据我在 XCode 调试器上得到这个值)和“\b”字符返回 -92
我知道退格键的ascii代码是int类型的“8”,所以我认为上面的函数就像下面的代码一样。
// 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
}
有谁可以一步步解释一下这段代码吗?
谢谢。
ref :
https://linux.die.net/man/3/strcmp
https://theasciicode.com.ar/ascii-control-characters/backspace-ascii-code-8.html
现在我可以理解为什么人们使用该代码,
并且上面的代码不正确。
尝试参考@Cristik的答案进行正确编辑。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// backspace checking
if string == "" {
return true // or false
}