How to Detect Backspace Event in UITextfield and UITextview?

by

In past I have used shouldChangeCharactersInRange delegate method to intercept the change in characters and make a near guess if it was delete-backspace that was tapped by the user. Guess was based on the nature of replacement character provided in method. If replacement character resembled the special escape character "\b" indicating backspace or empty character when view is already empty.

I felt above direction was a bit hacky. I found that based on response logic I was trying to write was giving me side effect of cursor always jumping to the end of text. For example when I tapped in between the characters of text to set the cursor in position and when I pressed backspace in keypad - I detected the event and did my processing to do some changes to text of UITextField and returned false.

What is the clean solution then?

You might also like: How to add a custom section header to a table view in Swift

You might also like: How to add a completion handler block for when I pop UIViewController?

The clean solution I found was to create a custom class inheriting UITextField or UITextView; and override deleteBackward to intercept delete event.

deleteBackward

Deletes a character from the displayed text. Remove the character just before the cursor from your class’s backing store and redisplay the text.


class CustomTextField: UITextField {
    override public func deleteBackward() {        
        // detect every backspace. Perform custom operation like calling delegate etc.
        super.deleteBackward()
    }
}



If I wanted to perform delete event check only for empty UITextField or empty UITextView then:


class CustomTextField: UITextField {
    override public func deleteBackward() {
        if text.isEmpty {
             // detect backspace on empty field. Perform custom operation like calling delegate etc.
        }
        super.deleteBackward()
    }
}

The same applies to UITextView too.

Some may be reluctant to go inheritance pattern than something like composition. But this is way cleaner than intercepting in shouldChangeCharactersInRange

You might also like: How to Send Local Video to iMessage in Swift

You might also like: AVAudioPlayer not playing any sound

You might also like: How to Get Substring With NSRange in Swift 5

You might also like: Adding two numbers in macOS x86-64 Assembly - Part 2

More Articles

Recommended posts