OTP screen problem, while entering and deleting characters

22 views Asked by At

I'm currently working on one project and I need to implement otp code there. I have searched for the screen setup in swift and found some code, but it does not correspond to all my needs.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let newLength = (textField.text?.count ?? 0) + string.count - range.length
    return newLength <= 1
}

@objc func textFieldDidChange(_ textField: UITextField) {
    if let text = textField.text, !text.isEmpty {
        switch textField {
        case firstField:
            secondField.becomeFirstResponder()
        case secondField:
            thirdField.becomeFirstResponder()
        case thirdField:
            fourthField.becomeFirstResponder()
        case fourthField:
            return
        default:
            break
        }
    } else {
        switch textField {
        case secondField:
            firstField.becomeFirstResponder()
        case thirdField:
            secondField.becomeFirstResponder()
        case fourthField:
            thirdField.becomeFirstResponder()
        default:
            break
        }
    }
}

this is the function that I use.

As you can see on this picture, I can enter the fourth character, but I can not delete it without entering the fourth one. If I want to delete the third number, I need either click on third field or enter the fourth to be able to delete the number.mHow can I solve it?

picture

0

There are 0 answers