How to achieve this UITextField layout/design used for SMS Verification Code?

rgoncalv picture rgoncalv · Feb 1, 2018 · Viewed 7.6k times · Source

I am trying to achieve the following functionality for SMS Verification code. How would I achieve it? After looking into a bunch of libraries in Github, none was similar enough to this design, which is widely used in the industry.

I tried implementing it with six textfields but found a number of problems as a lot of work, blocking all but the first textfield for initial input, laggy move of firstResponder and whatnot, what made me wonder if having 6 textfields is really the best approach.

Rounding the borders is piece of cake. The hard part is the functionality (i.e the cursor moving smoothly, getting back and forth, making all of them red when input is wrong, etc)

What do you guys think? How could I achieve such behavior/functionality?

enter image description here

Answer

user7832515 picture user7832515 · Feb 1, 2018

Try Below Code. (Currently it contains 4 UITextField, change it as per your requirement.)

extension ConfirmationCodeViewController: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if !(string == "") {
            textField.text = string
            if textField == txtFirst {
                txtSecond.becomeFirstResponder()
            }
            else if textField == txtSecond {
                txtThird.becomeFirstResponder()
            }
            else if textField == txtThird {
                txtForth.becomeFirstResponder()
            }
            else {
                textField.resignFirstResponder()
            }
            return false
        }
        return true
    }

    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if (textField.text?.count ?? 0) > 0 {

        }
        return true
    }
}