在 OTP 中,使用了四个文本字段。按下键盘后退按钮时将光标移动到上一个文本字段?
要检测 UITextField 中的退格事件,首先需要为 UITextField 设置委托并将其设置为 self。
class ViewController: UIViewController,UITextFieldDelegate
self.textField.delegate = self
然后使用下面的委托方法来检测是否按下了退格键
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let char = string.cString(using: String.Encoding.utf8)
let isBackSpace: Int = Int(strcmp(char, "\u{8}"))
if isBackSpace == -8 {
print("Backspace was pressed")
}
return true
}
基本上,此方法会检测您正在按下(或刚刚按下)的按钮。该输入以 NSString 形式出现。我们将此 NSString 转换为 C char 类型,然后将其与传统的退格字符 (\u{8}) 进行比较。那么如果这个strcmp等于-8,我们就可以将其检测为退格键。
choice 2
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if (string.characters.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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)