简体   繁体   English

Swift:如果用户达到最大字符,如何移动到下一个 UITextField

[英]Swift: How to move to next UITextField if the user reach max char

I'm trying to find a way that when the user reach to the maximum characters the text field move to next.我试图找到一种方法,当用户达到最大字符数时,文本字段会移动到下一个。

Here is my code:这是我的代码:

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
    }
    
}

Thanks谢谢

You can achieve that by doing something like this:您可以通过执行以下操作来实现这一点:

  1. create a function that will change your first responder when a character limit is reached创建一个函数,当达到字符限制时,该函数将更改您的第一响应者

     @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 } }
  2. Add that function to your textfield so it's triggered when the textfield is edited.将该函数添加到您的文本字段,以便在编辑文本字段时触发它。 In the above case, I added it to both textField1 and textField2在上面的例子中,我将它添加到 textField1 和 textField2

     textField1.addTarget(self, action: #selector(valueDidChange), for: .editingChanged) textField2.addTarget(self, action: #selector(valueDidChange), for: .editingChanged)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM