My goal here is to format the text as the user is typing
I am not completely sure how to use the
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool { }
I have tried several posibilities with this and the closer that I could get to what I want was the answer for this thread:
extension MyViewController: UITextFieldDelegate {
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
if let text = textField.text,
let textRange = Range(range, in: text) {
let updatedText = text.replacingCharacters(in: textRange,
with: string)
myvalidator(text: updatedText)
}
return true
}
}
I got really close to what I need. I can get the console to print the entered text and the new text for example
Input: 498746454
Console:
$ 0
4$ 4
49$ 49
498$ 498
4987$ 4 987
49874$ 49 874
498746$ 498 746
4987464$ 4 987 464
49874645$ 49 874 645
that's where my first problem is, because output is 1 character behind than the input in the textfield
How can I get it to change exactly when the text is inputed??
And my second question is how do I get it to display on the textfield??
This is the code I am using:
func myvalidator(text: String){
print(text)
}
func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let text = amount.text,
let textRange = Range(range, in: text) {
let updatedText = amount.text!.replacingCharacters(in: textRange, with: "$ \((amount.text! as NSString).doubleValue.formattedWithSeparator)")
myvalidator(text: updatedText)
}
return true
}
I did my research here, here, and here and several threads other but the answer either give me similar problems or are outdated for Swift 5