我有4个UITextFields
在一个UIView
中,就像这样:
每个UITextField
限制为4个字符。我想用每个UITextFields
的计数字符实现UITextField
之间的自动切换。
我使用shouldChangeCharactersIn
作为限制字符:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let maxLength = 4
var newString = String()
let currentString: NSString = textField.text! as NSString
newString = currentString.replacingCharacters(in: range, with: string)
return newString.length <= maxLength
}
这是我的开关装置:
func textFieldDidChange(_ textField: UITextField){
let text = textField.text
if text?.utf16.count == 4 {
switch textField {
case firstPartTextField:
secondPartTextField.becomeFirstResponder()
case secondPartTextField:
thirdPartTextField.becomeFirstResponder()
case thirdPartTextField:
fourthPartTextField.becomeFirstResponder()
default:
break
}
}
}
我的问题是在删除文本时切换到以前的
UITextField
,当UITextField
为空时,我无法检测到退格事件。 最佳答案
在viewDidLoad()中为textField添加目标
firstTxt.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: UIControlEvents.editingChanged)
secTxt.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: UIControlEvents.editingChanged)
thirdTxt.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: UIControlEvents.editingChanged)
fourTXt.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: UIControlEvents.editingChanged)
创建选择器方法
func textFieldDidChange(文本字段:UITextField){
let text = textField.text
if text?.utf16.count == 1{
switch textField{
case firstTxt:
secTxt.becomeFirstResponder()
case secTxt:
thirdTxt.becomeFirstResponder()
case thirdTxt:
fourTXt.becomeFirstResponder()
case fourTXt:
fourTXt.resignFirstResponder()
default:
break
}
}else{
}
}
关于ios - 使用Swift自动在UITextField之间切换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41912690/