I want to have commas dynamically added to my numeric UITextField entry while the user is typing.
For example: 123,456 and 12,345,678
Here is a solution in swift 4.
@objc func textFieldValDidChange(_ textField: UITextField) {
let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.decimal
if textField.text!.count >= 1 {
let number = Double(bottomView.balanceTxtField.text!.replacingOccurrences(of: ",", with: ""))
let result = formatter.string(from: NSNumber(value: number!))
textField.text = result!
}
}
Don't forget to add editingChanged action as below:
textField.addTarget(self, action:#selector(ViewController.textFieldValDidChange), for: .editingChanged)