I am searching for solutions on how to capture a backspace event, most Stack Overflow answers are in Objective-C but I need on Swift language.
First I have set delegate for the UITextField and set it to self
self.textField.delegate = self;
Then I know to use shouldChangeCharactersInRange
delegate method to detect if a backspace was pressed is all code are in Objective-C. I need in Swift these following method as below is used.
-(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;
}
Swift 4
Please don't trash your code. Just put this extension somewhere in your code.
Swift 5.1
And then just use it in your functions
Swift 4
Try this
Note: You can return "true" if you want to allow backspace. Else you can return "false".
I implemented this feature:
And in the case where the last textFiled is empty, I just want to switch to the previous textFiled. I tried all of the answers above, but no one works fine in my situation. For some reason, if I add more logic than
print
inisBackSpace == -92
parentheses block this method just stopped work...As for me the method below more elegant and works like a charm:
Swift
Thanks @LombaX for the answer