Swift 粘贴后自动更改文本字段

标签 swift uitextfield uicontrol

我设置了 3 个文本字段,我可以手动输入验证码,光标将在 4 个字符后移动到下一个文本字段。

但我也希望当我将代码粘贴到第一个文本字段时发生这种情况。目前它只会完全填充第一个字段,而不填充其他框

override func viewDidLoad() {
    super.viewDidLoad()
    //Get the users verification code form Firebase
    getCode()
    token1?.addTarget(self, action: #selector(TokenViewController.textFieldDidChange(_:)), for: UIControl.Event.editingChanged)
    token2?.addTarget(self, action: #selector(TokenViewController.textFieldDidChange(_:)), for: UIControl.Event.editingChanged)
    token3?.addTarget(self, action: #selector(TokenViewController.textFieldDidChange(_:)), for: UIControl.Event.editingChanged)

}

@objc func textFieldDidChange(_ textField: UITextField) {
    if textField == token1 {
        if (textField.text?.count)! >= 4 {
            token2?.becomeFirstResponder()
        }
    }
    else if textField == token2 {
        if (textField.text?.count)! >= 4 {
            token3.becomeFirstResponder()
        }
    }
    else if textField == token3{
        if (textField.text?.count)! >= 4 {
            token3.resignFirstResponder()
        }
    }
}

enter image description here

最佳答案

添加:

@objc func textFieldDidChange(_ textField: UITextField) {

        // ...


  if token1.text > 4 || token2.text > 4 || token3.text > 4 {

     let textFields = [token1, token2, token3]

      for token in textFields {

        if token.isFirstResponder {

     token1.text = token.text.prefix(4)
     token2.text = token.text.dropFirst(4).dropLast(4)
     token3.text = token.text.dropFirst(8)
                 }

            }
      }

}

关于Swift 粘贴后自动更改文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57270501/

相关文章:

ios - 如何导致NSString的dataUsingEncoding : method return nil?

iphone - 通过添加clickedButtonAtIndex导致UIAlertView崩溃

ios - UISegmentedControl 按钮停止工作

ios - 添加下拉菜单 iOS

ios - SWIFT:快速点击 UIButton 会导致选票计数不正确

Swift 编译器崩溃 : Illegal instruction: 4, 非规范或未经检查的类型

ios - 让 UITextField 更改 Webview URL

ios - 按下按钮(操作)3 秒后清除 urtext 字段中的数据

ios - 数据更改时如何对 UIControl 调整大小使用react

ios - 可以在 Codable 中使用 NSArray 吗? (将 "Object Mapper"转换为 "Codable")