Swift:如果用户达到最大字符数,如何移动到下一个 UITextField
Swift: How to move to next UITextField if the user reach max char
我正在尝试找到一种方法,当用户达到最大字符数时,文本字段将移至下一个。
这是我的代码:
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else {
return true
}
let length = text.count + string.count - range.length
let max = 2
if textField == weTextField {
return length <= max
}
else if textField == theyTextField {
return length <= max
}
return true
}
}
谢谢
您可以通过执行以下操作来实现:
创建一个函数,在达到字符数限制时更改您的第一响应者
@objc func valueDidChange(_ textField: UITextField) {
guard let text = textField.text else { return }
let maxLength = 2
switch textField {
case textField1 where text.count == maxLength:
textField2.becomeFirstResponder()
case textField2 where text.count == maxLength:
textField3.becomeFirstResponder()
default:
break
}
}
将该函数添加到您的文本字段,以便在编辑文本字段时触发它。在上面的例子中,我将它添加到 textField1 和 textField2
textField1.addTarget(self, action: #selector(valueDidChange), for: .editingChanged)
textField2.addTarget(self, action: #selector(valueDidChange), for: .editingChanged)
我正在尝试找到一种方法,当用户达到最大字符数时,文本字段将移至下一个。
这是我的代码:
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else {
return true
}
let length = text.count + string.count - range.length
let max = 2
if textField == weTextField {
return length <= max
}
else if textField == theyTextField {
return length <= max
}
return true
}
}
谢谢
您可以通过执行以下操作来实现:
创建一个函数,在达到字符数限制时更改您的第一响应者
@objc func valueDidChange(_ textField: UITextField) { guard let text = textField.text else { return } let maxLength = 2 switch textField { case textField1 where text.count == maxLength: textField2.becomeFirstResponder() case textField2 where text.count == maxLength: textField3.becomeFirstResponder() default: break } }
将该函数添加到您的文本字段,以便在编辑文本字段时触发它。在上面的例子中,我将它添加到 textField1 和 textField2
textField1.addTarget(self, action: #selector(valueDidChange), for: .editingChanged) textField2.addTarget(self, action: #selector(valueDidChange), for: .editingChanged)