Below is the code I am using to get the timer to fire and the keyboard to resign, THIS WORKS PERFECT ON ANY 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 device as the simulator, an iPhone 15 Pro). It will not resign the keyboard or fire the timer until I tap one extra digit on the keyboard and then it works perfect. It is not a deal breaker as it is obvious to any user to tap again on the keyboard to have it go away. Why does it work properly on all simulators, but not on my real 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) {
userInputTextField?.text = (userInputTextField?.text)! + " "
}
if (userInputTextField?.text?.count == 13) || (userInputTextField?.text?.count == 16) {
userInputTextField?.text = (userInputTextField?.text)! + ":"
}
// Mark check the condition to not exceed 19 chars
if let characterCount = userInputTextfield.text?.count {
// CHECK FOR CHARACTER COUNT IN TEXT FIELD
if characterCount >= 19 {
startCountdown((Any).self)
// RESIGN FIRST RERSPONDER TO HIDE KEYBOARD
return textField.resignFirstResponder()
}
}
}
}
I observe the same behaviour on simulator, only dismiss after char 20.
How do you test on simulator ? With physical keyboard or software keyboard (you should) ?
This is not the complete func textField() (we do not see all return). Please show it.
Could you add a log, to see what's happening ?
if textField == userInputTextField {
print("Count", userInputTextfield.text?.count)
Could you also try to change userInputTextfield to textField here
// Mark check the condition to not exceed 19 chars
if let characterCount = textField.text?.count {
I made it work by changing as follows:
if let characterCount = userInputTextfield.text?.count {
// CHECK FOR CHARACTER COUNT IN TEXT FIELD
if characterCount >= 18 {
// RESIGN FIRST RERSPONDER TO HIDE KEYBOARD
// Should test that string is a valid final char
if string.count == 1 && string.first!.isNumber {
userInputTextfield?.text = (userInputTextfield?.text)! + string
return textField.resignFirstResponder()
} else {
return false
}
}
}