I am using a UITextField that has a Decimal Pad Keyboard. So the user can only type in numbers. I would like the textfield to auto add commas to every thousand the user types. So that the user can easily identify how much they are typing. Is there a common way to do this?
Asked
Active
Viewed 2,750 times
2 Answers
4
here is the reference. below is the converted swift code. set the delegate to the textField and implement the delegate method below.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let cs = NSCharacterSet(charactersInString: "0123456789").invertedSet
let filtered = string.componentsSeparatedByCharactersInSet(cs)
let component = filtered.joinWithSeparator("")
let isNumeric = string == component
// check for input string is numeric value or either a number not a string or character.
if isNumeric {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.maximumFractionDigits = 10
let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
let numberWithOutCommas = newString.stringByReplacingOccurrencesOfString(",", withString: "")
let number = formatter.numberFromString(numberWithOutCommas)
if number != nil {
let formattedString = formatter.stringFromNumber(number!)
print(number)
print(formattedString)
textField.text = formattedString
} else {
textField.text = nil
}
}
return false
}

Community
- 1
- 1

Bhautik Ziniya
- 1,554
- 12
- 19
1
This answer should help. They have added commas in the shouldChangeCharactersInRange method. Here is the swift equivalent
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
let formattedNum = formatter.stringFromNumber(10000000)
textField.text = formattedNum
-
I am fairly new to iOS. I am not completely understanding. Why is there a number of 10,000,000? Also I tried entering 2nd line of code and Xcode is not picking it up. – CoderCody Jul 22 '16 at 02:47