Created
June 6, 2021 12:55
-
-
Save Catherine-K-George/c91e72eb46a260d5045eded3b47f38fd to your computer and use it in GitHub Desktop.
iOS Swift - OTP Auto fill to multiple textfields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { | |
var nextTextfieldTag = 0 | |
if string.isEmpty { | |
return true | |
} else if string.count == 1 { // Auto fill OTP to multiple textfield | |
textField.text = string | |
nextTextfieldTag = textField.tag + 1 | |
} else if string.count == maximumDigits { // Paste OTP to multiple textfield | |
var pastedOTP = string | |
for tag in 1...maximumDigits { | |
guard let textfield = view.viewWithTag(tag) as? UITextField else { continue } | |
textfield.text = String(pastedOTP.removeFirst()) | |
} | |
submitOTP() | |
} | |
if let nextTextfield = view.viewWithTag(nextTextfieldTag) as? UITextField { | |
nextTextfield.becomeFirstResponder() | |
} else { | |
if nextTextfieldTag > maximumDigits { submitOTP() } | |
view.endEditing(true) | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment