I am subclassing UITextField to create a currency text field. The text field auto formats number being entered into currency as it is being typed. I've got it working with one issue. For whatever reason the last number typed gets doubled. Say for example I want enter $56.78, so I key in 5678, however the output ends up being $56.788.
I've printed every possible scenario to the console and the correct version prints there (in this case 56.78). I've narrowed it down I believe to the formatCurrency function but I cannot figure out for the life of me what is going on. Here is the relevant code:
class CurrencyTextField: UITextField, UITextFieldDelegate {
private var currencyString = String()
func textFieldDidBeginEditing(_ textField: UITextField) {
// Clear out the current string when the user starts editing the field
//currencyString = ""
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
switch string {
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
currencyString += string
self.text = formatCurrency(currencyString)
return true
default:
return false
}
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
// Clear the current string if the user clicks the clear button
currencyString = ""
return true
}
private func formatCurrency(_ string: String) -> String {
let numberToFormat = Double(string)! / 100
let formatter = NumberFormatter()
formatter.numberStyle = .currency
if let stringToReturn = formatter.string(from: NSNumber(value: numberToFormat)) {
return stringToReturn
} else {
return "$0.00"
}
}
}
Any insight would be highly appreciated! I used very similar code without subclassing and didn't have any issues. Additionally, if I bypass the formatting and just use a straight number it works as well.
BONUS if you have any thoughts on why given this same code that the backspace key on the number pad doesn't work.
EDIT: This is not a duplicate as marked as the case it was said to duplicate shows how to do what I am already doing, it doesn't even mention the problem I am having.