在 TextField iOS 中按 Backspace/Delete

Pressing Backspace/Delete in TextField iOS

我正在尝试使用它,以便当用户在输入 PIN 码时按下 "backspace/delete" 按钮时,它会转到并删除 "previous" 文本字段。我在 SO 上看到了其他解决方案,函数 keyboardInputShouldDelete 似乎很有希望,但它没有用。任何帮助是极大的赞赏。下面是我的代码:

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

            if ((textField.text?.count)! < 1) && (string.count > 0) {

                if textField == txtOTP1 {

                    txtOTP2.becomeFirstResponder()
                }

                if textField == txtOTP2 {

                    txtOTP3.becomeFirstResponder()
                }
                if textField == txtOTP3 {

                    txtOTP4.becomeFirstResponder()

                }
                if textField == txtOTP4 {

                    check()

                }

                textField.text = string

                userPIN = "\(self.txtOTP1.text!)\(self.txtOTP2.text!)\(self.txtOTP3.text!)\(self.txtOTP4.text!)"

                return false

            } else if ((textField.text?.count)! >= 1) && (string.count == 0) {

                if textField == txtOTP4 {

                    txtOTP3.becomeFirstResponder()
                }

               if textField == txtOTP3 {

                    txtOTP2.becomeFirstResponder()

                }

              if textField == txtOTP2 {

                    txtOTP1.becomeFirstResponder()

                }

               if textField == txtOTP1 {

                }

                textField.text = ""

                return false

            }

            else if (textField.text?.count)! >= 1 {

                textField.text = string

                return false
            }

            return true

        }

 func keyboardInputShouldDelete(_ textField: UITextField) -> Bool {

        textField.delegate = self

        return true
    }

尝试这样做:

//Get new length of the text after input
let newLength = (textField.text ?? "").count + string.count - range.length
if newLength == 0 {
    //Go back prev textfield if new length is 0
}

为了克服 shouldChangeCharactersIn 不会在空字段上调用的问题,只需将用户输入的最后一个字符从上一个文本字段带到下一个文本字段,这样用户就不会再有空字段了第一个文本框。

另一种方法是默认为每个文本字段添加一个 space 字符并在其周围进行检测,但处理起来似乎更烦人。