2

As my question title, I want to know the user click the delete button like following image.
Thanks.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

   if text == "" {
       print("Text is null")
   } 
}

image here.

Beginnerrrrrr
  • 537
  • 1
  • 8
  • 27

2 Answers2

5

UITextField conforms to UITextInput protocol which in terms inherits from UIKeyInput protocol. UIKeyInput protocol has func deleteBackward() function which is called when user press delete button on the keyboard.

Create a custom subclass that inherits from UITextField and do your work inside that function. May be notify your event handler through your custom delegate or something.

class YourCustomTextField: UITextField {

    override func deleteBackward() {
        super.deleteBackward()
        // do your work here
    }

}

Remember to call super.deleteBackward() so that it will delete a single character or selected range of characters when user tap delete button. If you didn't call, the text wont change when user taps the delete button.

Cosmos Man
  • 593
  • 3
  • 15
3

Compare the count of characters of textField and result string after replacement

var txtBeforeUpdate:NSString = textField.text as NSString!

var txtAfterUpdate = txtAfterUpdate.replacingCharacters(in: range,     with: string) as NSString

Also the best way:

let  char = string.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")

if (isBackSpace == -92) {
     print("Backspace was pressed")
}
nerowolfe
  • 4,787
  • 3
  • 20
  • 19