rengineer
rengineer

Reputation: 359

Pressing Backspace/Delete in TextField iOS

I am trying to have it so that when a user presses the "backspace/delete" button when they're inputting a PIN number, it goes to and deletes the "previous" textfield. I saw other solutions on SO and the function keyboardInputShouldDelete seemed promising but it didn't work. Any help is greatly appreciated. Below is my code:

     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

            if ((textField.text?.count)! < 1) && (string.count > 0) {

                if textField == txtOTP1 {

                    txtOTP2.becomeFirstResponder()
                }

                if textField == txtOTP2 {

                    txtOTP3.becomeFirstResponder()
                }
                if textField == txtOTP3 {

                    txtOTP4.becomeFirstResponder()

                }
                if textField == txtOTP4 {

                    check()

                }

                textField.text = string

                userPIN = "\(self.txtOTP1.text!)\(self.txtOTP2.text!)\(self.txtOTP3.text!)\(self.txtOTP4.text!)"

                return false

            } else if ((textField.text?.count)! >= 1) && (string.count == 0) {

                if textField == txtOTP4 {

                    txtOTP3.becomeFirstResponder()
                }

               if textField == txtOTP3 {

                    txtOTP2.becomeFirstResponder()

                }

              if textField == txtOTP2 {

                    txtOTP1.becomeFirstResponder()

                }

               if textField == txtOTP1 {

                }

                textField.text = ""

                return false

            }

            else if (textField.text?.count)! >= 1 {

                textField.text = string

                return false
            }

            return true

        }

 func keyboardInputShouldDelete(_ textField: UITextField) -> Bool {

        textField.delegate = self

        return true
    }

Upvotes: 0

Views: 1437

Answers (1)

Tj3n
Tj3n

Reputation: 9923

Try do it like this:

//Get new length of the text after input
let newLength = (textField.text ?? "").count + string.count - range.length
if newLength == 0 {
    //Go back prev textfield if new length is 0
}

To overcome the issue where the shouldChangeCharactersIn won't get called on empty field, simply carry the last character user input from last textfield to the next, so user will never have an empty field aside from the first textfield.

Another way is add a space character by default for each textfield and detect around it but it seems to be more annoying to dealt with.

Upvotes: 1

Related Questions