检测哪个字符在Swift中退格

时间:2016-01-02 02:31:56

标签: ios swift

我想在用户退回@密钥时检测到。我正在使用的代码是:

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
    }

..但它没有告诉我哪个键是退格的。有什么办法吗?

1 个答案:

答案 0 :(得分:5)

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
    }