我有四个textField用于OTP,并且还在ViewDidLoad()方法中将委托设置为我的viewcontroller
我还实现了委托方法:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if string.characters.count > 1 {
return false
} else {
var tag = textField.tag
if string.characters.count == 0 {
tag -= 1
} else {
tag += 1
}
textField.text = string
// Try to find next responder
let nextResponder = textField.superview?.viewWithTag(tag) as UIResponder!
nextResponder?.becomeFirstResponder()
}
return false
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
print("BACKSPACE PRESSED")
return true
}
但是当字段为空时,这两种方法都不会调用,实际上我想要明文。任何想法如何检测"退格"在textfield为空时按下
答案 0 :(得分:1)
有检测退格的代码
345
答案 1 :(得分:1)
直接识别退格是不正确的逻辑。根据您的要求,您的文本字段变为空白,然后您希望以前的文本字段成为第一响应者,然后您需要像这样编写代码
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var txtAfterUpdate:NSString = textField.text! as NSString
txtAfterUpdate = txtAfterUpdate.replacingCharacters(in: range, with: string) as NSString
let updatedString = txtAfterUpdate as String
if updatedString.characters.count == 0 {
var tag = textField.tag
tag -= 1
let nextResponder = textField.superview?.viewWithTag(tag) as UIResponder!
nextResponder?.becomeFirstResponder()
return true
} else{
// rest of your functionality
}
return true
}
我希望它会对你有所帮助。
答案 2 :(得分:1)
我通过覆盖UITextField的Follow Method来获得解决方案。
class MYTextField: UITextField {
override func deleteBackward() {
super.deleteBackward()
delegate?.textFieldShouldReturn!(self)
print("_____________BACKSPACE_PRESSED_____________")
}
}