Detect backspace Event in UITextField

后端 未结 11 604
自闭症患者
自闭症患者 2020-12-04 16:35

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

11条回答
  •  长情又很酷
    2020-12-04 17:23

    Swift 5.3

    In some version its changed and now it says:

    When the user deletes one or more characters, the replacement string is empty.

    So answer for this:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
      if string.isEmpty {
        // do something
      }
      return true
    }
    

    If you want to detect that some characters will be deleted

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
      if range.length > 0 {
        // We convert string to NSString instead of NSRange to Range
        // because NSRange and NSString not counts emoji as one character
        let replacedCharacters = (string as NSString).substring(with: range)
      }
      return true
    }
    

    If you want detect backspaces even on empty textField

    class TextField: UITextField {
      var backspaceCalled: (()->())?
      override func deleteBackward() {
        super.deleteBackward()
        backspaceCalled?()
      }
    }
    

    Old answer

    Please don't trash your code. Just put this extension somewhere in your code.

    extension String {
      var isBackspace: Bool {
        let char = self.cString(using: String.Encoding.utf8)!
        return strcmp(char, "\\b") == -92
      }
    }
    

    And then just use it in your functions

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
      if string.isBackspace {
        // do something
      }
      return true
    }
    

提交回复
热议问题