我希望在用户退格@
键时检测到.我正在使用的代码是:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let char = string.cStringUsingEncoding(NSUTF8StringEncoding)! let isBackSpace = strcmp(char, "\\b") if (isBackSpace == -92) { print("Backspace was pressed") } return true }
..但它没有告诉我哪个键是退格的.有什么办法吗?
Backspace不会出现在replacementString
参数中.系统通过指定要删除的范围(将跨越单个组合字符序列,除非用户选择了一系列文本),使用替换字符串""
(空字符串)来实现退格.因此,要检测退格或其他删除操作:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if string == "" && range.length > 0 { // Backspace or other deletion let stringToDelete = (textField.text! as NSString).substringWithRange(range) if stringToDelete == "@" { print("bye-bye @") } } return true }