Swift why strcmp of backspace returns -92?

时光总嘲笑我的痴心妄想 提交于 2019-12-04 12:39:23

Let's analyze a little bit the code and the data that flows through that code:

  1. string is an empty string, as when you delete a character, the textfield tries to replace it by "nothing" (an empty string)
  2. due to #1, char holds only the string terminator, which is \0, in memory: [0]
  3. "\\b" translates to the \b string, in memory: [92, 98]
  4. due to #2 and #3, strcmp returns 0 - 92 => -92.

Not sure why people use this "algorithm", when they could simply check for the emptiness of the string parameter. I assume they firstly tried to use the \b escape sequence, which doesn't seem to be a valid one, so they added an extra \ character, which compiled, but resulted in an incorrect escape sequence, as \\ is the escaping sequence for the backslash character, resulting in the b part being represented as the plain letter.

Seems that backspace is not reported by the delegate method, instead the delegate method is asked to operate on strings. Detecting the actual key press might need some UIEvent/RunLoop hooks.

Note that an empty string passed to textField(_,shouldChangeCharactersIn:,replacementString:) doesn't always mean that backspace was presset, a cut operation might result too in an empty string being sent to the delegate. You could try and check the range and assume that for a range of 1 backspace was pressed, however the user can also cut one character...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!