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 deleg
I find the comparison using strcmp
irrelevant. We don't even know how strcmp
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 Version 9.3 (9E145)
using Swift 4.1
)
FYI : Every character that you actually type is an array of 1
or more elements in utf8 Encoding
. backSpace Character is [0]
. You can try this out.
PS : Don't forget to assign the proper delegates
to your textFields
.
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let char = string.cString(using: String.Encoding.utf8)!
if (char.elementsEqual([0])) {
print("Backspace was pressed")
}
else {
print("WHAT DOES THE FOX SAY ?\n")
print(char)
}
return true
}