0

As the title in this question. I want to check if delete key is pressed. I knew about this code below:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

     if string.characters.count == 0 && range.length > 0 {
          // Back pressed
          print("OK")
     }

     return true
}

But when the textField is empty, this function is not called. So, how to check that case?

Thanks

TienLe
  • 614
  • 2
  • 9
  • 33
  • 1
    Why do you need to check a backspace character when the textfield is empty? – unkgd Feb 20 '17 at 13:56
  • 1
    This function will not work if textField is empty. – Prema Janoti Feb 20 '17 at 14:00
  • @unkgd When textfield is empty and the backspace was pressed. I will remove something like tag/hashtag... – TienLe Feb 20 '17 at 14:01
  • 1
    @TienLe, did you check this post: http://stackoverflow.com/questions/1977934/detect-backspace-in-uitextfield – unkgd Feb 20 '17 at 14:03
  • @PremaJanoti: Yes, the function is not called – TienLe Feb 20 '17 at 14:05
  • @unkgd: I know the charactor \u200B. This is backspace. But how to detect this charactor? – TienLe Feb 20 '17 at 14:06
  • What they are mentioning in the post, is that you should use an empty character placeholder when the last character is deleted, this way you always have a character which is "empty" in the text field, and each time you delete it, put a new replacement – unkgd Feb 20 '17 at 14:07
  • @unkgd: I understand. Thanks for your answer. Have a good day :) override func deleteBackward() { super.deleteBackward()} It works – TienLe Feb 20 '17 at 14:15

1 Answers1

-1

You can try it

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

      if (string.Charecter.count==0) { //Delete any cases
       if(range.length > 1){
          //Delete whole word
       }
       else if(range.length == 1){
          //Delete single letter
       }
       else if(range.length == 0){
          //Tap delete key when textField empty
       }  
    }  
    return true
}
Ram
  • 961
  • 6
  • 14