Skip to content

Instantly share code, notes, and snippets.

@Catherine-K-George
Created June 6, 2021 12:55
Show Gist options
  • Save Catherine-K-George/c91e72eb46a260d5045eded3b47f38fd to your computer and use it in GitHub Desktop.
Save Catherine-K-George/c91e72eb46a260d5045eded3b47f38fd to your computer and use it in GitHub Desktop.
iOS Swift - OTP Auto fill to multiple textfields
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