我正在尝试使用它,以便当用户在输入 PIN 码时按下“退格/删除”按钮时,它会转到并删除“上一个”文本字段。我在 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
不会在空字段上被调用的问题,只需将用户输入的最后一个字符从上一个文本字段带到下一个文本字段,这样用户就永远不会有空字段第一个文本框。
另一种方法是默认为每个文本字段添加一个空格字符并在其周围进行检测,但处理起来似乎更烦人。
关于ios - 在 TextField iOS 中按退格键/删除键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51855640/