1

I have a few textfields with decimal keyboards, I want to make them showing $ and comma ($1,222,000.00) in the screen. And also change the spacing of the text because when added comma it will be crowded.

for textField in self.numberTextField! as [UITextField] {
        textField.keyboardType = .DecimalPad
        textField.inputAccessoryView = keyboardToolbar

numberTextField is my collection of the textfields. Any help appreciated! Thanks a lot!

user6702783
  • 223
  • 4
  • 14
  • 1
    http://stackoverflow.com/questions/29782982/how-to-input-currency-format-on-a-text-field-from-right-to-left-using-swift/29783546?s=1|0.1094#29783546 – Leo Dabus Aug 18 '16 at 05:12

1 Answers1

3
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let oldText = textField.text! as NSString
    var newText = oldText.stringByReplacingCharactersInRange(range, withString: string) as NSString!
    var newTextString = String(newText)

    let digits = NSCharacterSet.decimalDigitCharacterSet()
    var digitText = ""
    for c in newTextString.unicodeScalars {
        if digits.longCharacterIsMember(c.value) {
            digitText.append(c)
        }
    }

    let formatter = NSNumberFormatter()
    formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
    formatter.locale = NSLocale(localeIdentifier: "en_US")
    let numberFromField = (NSString(string: digitText).doubleValue)/100
    newText = formatter.stringFromNumber(numberFromField)

    textField.text = String(newText)

    return false

}
Nitesh
  • 1,564
  • 2
  • 26
  • 53
  • You are creating a new NSNumberFormatter object everytime the field changes – Leo Dabus Aug 18 '16 at 05:10
  • Hi, where should I add these codes? In the loop mentioned in the question or in the viewcontroller class? – user6702783 Aug 18 '16 at 05:47
  • In you ViewController. Remove that for loop. Just add UITextFieldDelegate and confirm that. After that use the above code. – Nitesh Aug 18 '16 at 05:50
  • I use @IBOutlet var numberTextField: Array?, in the formatCurrency function, the self.numberTextField.text has an error said Array? has no member 'text'. – user6702783 Aug 18 '16 at 05:56
  • I added "class CashflowViewController: UIViewController, UITextFieldDelegate", is it correct? – user6702783 Aug 18 '16 at 06:02
  • Right you TextField on your Storyboard then drag it into ViewController and select delegate. Edited the code, try that. – Nitesh Aug 18 '16 at 06:10
  • Hi, your code is fine. But when I input something and delete, there will always be a $0.00 which cannot be removed. – user6702783 Aug 22 '16 at 05:42
  • What do you mean by input something and delete ? For obvious there will be $0.00 if nothing is passed. What you are trying to do ? Can you please elaborate. – Nitesh Aug 22 '16 at 05:45