I am trying to get the keyboard to resign and start the timer countdown automatically when the user inputs 19 characters

51 Views Asked by At

Below is the code I am using to get the timer to fire and the keyboard to resign, this works great on the simulator. I type in 02272024075900 and it populates 02/27/2024 07:59:00 as soon as I type the last zero the keyboard resigns and the timer fires.

But when I run it on my handheld(same as simulator iPhone 15 Pro)device I have to add one extra tap on the keyboard to get it to work. I cannot understand why it works properly on all simulators, but not on my device.

Any thoughts greatly appreciated.

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

    if textField == userInputTextField {

            if (userInputTextField?.text?.count == 2) || (userInputTextField?.text?.count == 5) {
                if !(string == "") {
                    userInputTextField?.text = (userInputTextField?.text)! + "/"
                }
            }
            if (userInputTextField?.text?.count == 10) {
                if !(string == "") {
                    userInputTextField?.text = (userInputTextField?.text)! + " "

                }
            }
            if (userInputTextField?.text?.count == 13) || (userInputTextField?.text?.count == 16) {
                if !(string == "") {
                    userInputTextField?.text = (userInputTextField?.text)! + ":"
                }
            }
        
            // Mark check the condition to not exceed 19 chars
            if let characterCount = textField.text?.count {
                // CHECK FOR CHARACTER COUNT IN TEXT FIELD
                if characterCount >= 19 {
                    startCountdown((Any).self)
                    // RESIGN FIRST RERSPONDER TO HIDE KEYBOARD
                    return textField.resignFirstResponder()
            }
        }
    }
}
0

There are 0 best solutions below