I have a UITextField with a formatted string.
I can't figure out why a backspace press works fine for every character deletion except the first character?
My code:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let formatter = NumberFormatter()
formatter.usesGroupingSeparator = true
formatter.numberStyle = .decimal
formatter.decimalSeparator = "."
formatter.groupingSeparator = " "
let textString = textField.text ?? ""
guard let range = Range(range, in: textString) else { return false }
let updatedString = textString.replacingCharacters(in: range, with: string)
let completeString = updatedString.replacingOccurrences(of: formatter.groupingSeparator, with: "")
guard let value = Double(completeString) else { return false }
numberFromTextField = value
let formattedNumber = formatter.string(from: NSNumber(value: value)) ?? ""
textField.text = formattedNumber
return string == formatter.decimalSeparator
}
A gif with the problem behaviour: CLICK
Where is my error hides?