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
I find the comparison using
strcmp
irrelevant. We don't even know howstrcmp
is operating behind the hoods.In all the other answers when comparing current char and\b
results are-8
in objective-C and-92
in Swift. I wrote this answer because the above solutions did not work for me. ( Xcode Version9.3 (9E145)
using Swift4.1
)FYI : Every character that you actually type is an array of
1
or more elements inutf8 Encoding
. backSpace Character is[0]
. You can try this out.PS : Don't forget to assign the proper
delegates
to yourtextFields
.Swift 4: If the user presses the backspace button, string is empty so this approach forces textField to only accept characters from a specified character set (in this case utf8 characters) and backspaces (string.isEmpty case).
Swift 4.2
Older Swift version
In Swift 3
:)
I prefer subclassing
UITextField
and overridingdeleteBackward()
because that is much more reliable than the hack of usingshouldChangeCharactersInRange
:The
shouldChangeCharactersInRange
hack combined with an invisible character that is placed in the text field has several disadvantages:Shift Arrow
on a keyboard or even by tapping on the caret) and will be confused about that weird character,placeholder
isn't shown anymore,clearButtonMode = .whileEditing
.Of course, overriding
deleteBackward()
is a bit inconvenient due to the need of subclassing. But the better UX makes it worth the effort!And if subclassing is a no-go, e.g. when using
UISearchBar
with its embeddedUITextField
, method swizzling should be fine, too.If u need detect backspace even in empty textField (for example in case if u need auto switch back to prev textField on backSpace pressing), u can use combination of proposed methods - add invisible sign and use standard delegate method
textField:shouldChangeCharactersInRange:replacementString:
like followCreate invisible sign
Set delegate for textField
On event
EditingChanged
check text and if needed add invisible symbol like follow:Add implementation of delegate method
textField:shouldChangeCharactersInRange:replacementString: