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
For Swift 4.0 Version of Lyndsey Scott's answer:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if ((string == "0" || string == "") && (textField.text! as NSString).range(of: ".").location < range.location) {
return true
}
// First check whether the replacement string's numeric...
let cs = NSCharacterSet(charactersIn: "0123456789.").inverted
let filtered = string.components(separatedBy: cs)
let component = filtered.joined(separator: "")
let isNumeric = string == component
// Then if the replacement string's numeric, or if it's
// a backspace, or if it's a decimal point and the text
// field doesn't already contain a decimal point,
// reformat the new complete number using
if isNumeric {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 8
// Combine the new text with the old; then remove any
// commas from the textField before formatting
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let numberWithOutCommas = newString.replacingOccurrences(of: ",", with: "")
let number = formatter.number(from: numberWithOutCommas)
if number != nil {
var formattedString = formatter.string(from: number!)
// If the last entry was a decimal or a zero after a decimal,
// re-add it here because the formatter will naturally remove
// it.
if string == "." && range.location == textField.text?.count {
formattedString = formattedString?.appending(".")
}
textField.text = formattedString
} else {
textField.text = nil
}
}
return false
}