uitextfield: the cursor scrolls to finalize the edition of the formatted decimal text field: Swift

I am formatting a text field so that it is separated with commas (decimal style) while it is being written.

So 12345678 becomes 12,345,678

Now when you edit the text field, say I want to delete 5, then I tap later 5 and delete it, but the cursor moves to the end of the text immediately, that's after 8.

Here is my code that I used to format the decimal as I write:

func checkTextField (_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if ((string == "0" || string == "") && (textField.text! as NSString) .range (of: "."). location <range.location) {
return true
}
let allowedCharacterSet = NSCharacterSet (charactersIn: "0123456789."). invested
let filter = string.components (separatedBy: allowedCharacterSet)
leave component = filtered. united (separator: "")
let isNumeric = string == component
if it is numeric {
leave formatter = NumberFormatter ()
formatter.numberStyle = .decimal
let newString = (textField.text! as NSString) .replacingCharacters (in: range, with: string)
let numberWithOutCommas = newString.replacingOccurrences (of: ",", with: "")
let number = formatter.number (from: numberWithOutCommas)
yes number! = nil {
var formattedString = formatter.string (from: number!)
if string == "." && range.location == textField.text? .count {
formattedString = formattedString? .appending (".")
}
textField.text = formattedString
} else {
textField.text = nil
}
}
false return
}

It is called like this:

func textField (_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
go to textFieldText = (textField.text! as NSString) .replacingCharacters (in: range, with: string)
leave checkForCurrency = checkTextField (textField, shouldChangeCharactersIn: range, replacementString: string)
return
}

I have tried the following but in vain:

Solution 1

Solution 2

What could be the reason for the change of cursor?
Any help would be appreciated!