I am working on an app in which I have to pass 6 digits OTP through 6 textFields
in which you to provide only one character and after that it automatically goes to another textField
. I created 6 textFields outlets and used this code.
override func viewDidLoad() {
super.viewDidLoad()
txtOTP1.delegate = self
txtOTP2.delegate = self
txtOTP3.delegate = self
txtOTP4.delegate = self
txtOTP5.delegate = self
txtOTP6.delegate = self
}
And I used this logic to create the functionality
func textField(_ textField: UITextField, shouldChangeCharactersIn range:NSRange, replacementString string: String) -> Bool {
// Range.length == 1 means,clicking backspace
if (range.length == 0){
if textField == txtOTP1 {
txtOTP2?.becomeFirstResponder()
}
if textField == txtOTP2 {
txtOTP3?.becomeFirstResponder()
}
if textField == txtOTP3 {
txtOTP4?.becomeFirstResponder()
}
if textField == txtOTP4 {
txtOTP5?.becomeFirstResponder()
}
if textField == txtOTP5 {
txtOTP6?.becomeFirstResponder()
}
if textField == txtOTP6 {
txtOTP6?.resignFirstResponder()
}
textField.text? = string
return false
}else if (range.length == 1) {
if textField == txtOTP6 {
txtOTP5?.becomeFirstResponder()
}
if textField == txtOTP5 {
txtOTP4?.becomeFirstResponder()
}
if textField == txtOTP4 {
txtOTP3?.becomeFirstResponder()
}
if textField == txtOTP3 {
txtOTP2?.becomeFirstResponder()
}
if textField == txtOTP2 {
txtOTP1?.becomeFirstResponder()
}
if textField == txtOTP1 {
txtOTP1?.resignFirstResponder()
}
textField.text? = ""
return false
}
return true
}
But it is very long and messy. Is there anyway I can make it simple?