一尘不染

在UITextField中检测退格事件

swift

我正在寻找有关如何捕获退格事件的解决方案,大多数堆栈溢出答案都在Objective-C中,但是我需要使用Swift语言。

首先,我为UITextField设置了委托,并将其设置为self

self.textField.delegate = self;

然后,我知道使用shouldChangeCharactersInRange委托方法来检测是否按下了退格键,因为所有代码都在Objective-
C中。我需要在Swift中使用以下方法。

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    const char * _char = [string cStringUsingEncoding:NSUTF8StringEncoding];
    int isBackSpace = strcmp(_char, "\b");

    if (isBackSpace == -8) {
        // NSLog(@"Backspace was pressed");
    }

    return YES;
}

阅读 355

收藏
2020-07-07

共1个答案

一尘不染

斯威夫特4.2

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if let char = string.cString(using: String.Encoding.utf8) {
        let isBackSpace = strcmp(char, "\\b")
        if (isBackSpace == -92) {
            print("Backspace was pressed")
        }
    }
    return true
}

较早的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) {
        println("Backspace was pressed")
    }
    return true
}
2020-07-07