首页 > 解决方案 > 如果我们使用多个文本字段,如何自动获取 OTP

问题描述

我知道如果我们想自动获取 OTP(如果我们使用单个文本字段),我们需要使用

otpTextField.textContentType = .oneTimeCode

但是,如果我们使用多个文本字段(根据下图)

像这样的东西

我们应该如何做到这一点?

标签: iosswiftuitextfieldone-time-password

解决方案


-> 从 iOS 12 开始,Apple 将允许支持读取您将在 iPhone 设备中获得的一次性代码。您可以将文本拆分为四个字段并自动填充并手动输入 otp 并逐个删除并移动每个文本字段。

1) self.textone 最大长度 4 和其他文本字段最大长度 1

2) 添加 UITextFieldDelegate

在此处输入图像描述

if #available(iOS 12.0, *) {
   txtOne.textContentType = .oneTimeCode
}
self.txtOne.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
self.txtOne.becomeFirstResponder()

  @objc func textFieldDidChange(_ textField: UITextField) {
    if #available(iOS 12.0, *) {
        if textField.textContentType == UITextContentType.oneTimeCode{
            //here split the text to your four text fields
            if let otpCode = textField.text, otpCode.count > 3{
                txtOne.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 0)])
                txtTwo.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 1)])
                txtThree.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 2)])
                txtFour.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 3)])
            }
        }
     } 
  }

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

       if (string.count == 1){
           if textField == txtOne {
               txtTwo?.becomeFirstResponder()
           }
           if textField == txtTwo {
               txtThree?.becomeFirstResponder()
           }
           if textField == txtThree {
               txtFour?.becomeFirstResponder()
           }
           if textField == txtFour {
               txtFour?.resignFirstResponder()
               textField.text? = string
                //APICall Verify OTP
               //Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.VerifyOTPAPI), userInfo: nil, repeats: false)
           }
           textField.text? = string
           return false
       }else{
           if textField == txtOne {
               txtOne?.becomeFirstResponder()
           }
           if textField == txtTwo {
               txtOne?.becomeFirstResponder()
           }
           if textField == txtThree {
               txtTwo?.becomeFirstResponder()
           }
           if textField == txtFour {
               txtThree?.becomeFirstResponder()
           }
           textField.text? = string
           return false
       }

   }

推荐阅读