How to auto fetch OTP, if we use multiple text fields

喜你入骨 提交于 2019-12-10 03:24:20

问题


I know that if we want to auto fetch the OTP(if we use single textfield) we need to use

otpTextField.textContentType = .oneTimeCode

But, If we use multiple textfield(According to following image)

how should we achieve this ?


回答1:


If you can get the auto OTP for single field, you can split that text into your four text fields. I believe.

You may have to use textField's change observer as like below,

textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
func textFieldDidChange(_ textField: UITextField) {

        // here check you text field's input Type
        if textField.textContentType == UITextContentType.oneTimeCode{

            //here split the text to your four text fields

            if let otpCode = textField.text, otpCode.count > 3{

                textField.text = String(otpCode[otpCode.startIndex])
                textField1.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 1)])
                textField2.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 2)])
                textField3.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 3)])
        }
    }

}



回答2:


What I do is similar to @Natarajan's answer, but I use UITextFieldDelegate method. On viewDidAppear your first text field should become first responder and be of type oneTimeCode.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {        
    // Fill your textfields here

    return true
}


来源:https://stackoverflow.com/questions/53413385/how-to-auto-fetch-otp-if-we-use-multiple-text-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!