Detect Backspace Event in TextField on iOS

Asif Ahmed

Over the past few months, I’ve been heavily focusing on iOS development and the next few posts will reflect that. This post will briefly cover a problem I was having a couple days ago on how to detect a backspace event in a UITextField. I was trying to figure how to capture this backspace event because whenever I pressed backspace, I wanted two characters to be deleted. When I was searching for solutions on how to capture a backspace event, most StackOverflow answers wanted you to subclass the UITextField. I felt like there had to be a better answer, and with a bit more researching I found it!

To detect the backspace event in a UITextField, first you need to set up a delegate for the UITextField and set it to self.

Then you use the delegate method below to detect if a backspace was pressed.

Basically this method detects which button you are pressing (or have just pressed). This input comes in as an NSString. We convert this NSString to a C char type and then compare it to the traditional backspace character (\b). Then if this strcmp is equal to -8, we can detect it as a backspace.

I know this looks absolutely wonky, but it works and it works more easily than other solutions suggested (because who wants to subclass a class just for one piece of functionality that can be easily taken care of otherwise).

If you want to see a working example, checkout the code I posted on Github – https://github.com/sifxtreme/backspace-iOS-textfield

If you want to see additional links regarding this issue and see other solutions check out the links below.

http://stackoverflow.com/questions/1977934/detect-backspace-in-uitextfield

http://stackoverflow.com/questions/16765334/ios-6-uitextfield-secure-how-to-detect-backspace-clearing-all-characters

Have you guys found a better solution? Let me know in the comments.

 

  • Surendra Bobbepalli

    its helped me alot

  • komocode

    doesn’t work on empty text field and user presses backspace.