1

I currently have two separate text fields in my app and I am trying to change it to only one. The text fields are used for inputting currency (one for pound, dollar, euro etc. and one for pence, cent etc.) and they work fine, however I need to add some functionality that won't be possible unless I use a single text field. Plus, I think a single text field is more user friendly.

Basically I would like to have a text field that formats in real time in currency form localised for the user while they are typing. Eg.

1 formats as £1.00 or $1.00 or 1.00€ etc... 1000 formats as £1,000.00 or $1,000.00 or 1 000,00€ etc...

I've done some research and found a few Objective-C examples, but I just can't figure out how to do the same thing in Swift (I've never programmed in Objective-C).

Any help would be very much appreciated as I have found this rather frustrating.

user3746428
  • 11,047
  • 20
  • 81
  • 137

1 Answers1

4

You can use this code:

func currencyStringFromNumber(number: Double) -> String {
    let formatter = NSNumberFormatter()
    formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
    formatter.currencyCode = NSLocale.currentLocale().displayNameForKey(NSLocaleCurrencySymbol, value: NSLocaleCurrencyCode)
    return formatter.stringFromNumber(number)
}

let currencyString = currencyStringFromNumber(21010)
println("Currency String is: \(currencyString)")

// Will print $21,010.00

Here's a compilable and working example of this information extrapolated to work as you require.

import UIKit

class CurrencyTextFieldExample: UIViewController {

    let currencyFormatter = NSNumberFormatter()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let textField = UITextField()
        textField.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
        textField.frame = CGRect(x: 0, y: 40, width: 320, height: 40)
        textField.keyboardType = UIKeyboardType.NumberPad
        textField.backgroundColor = UIColor.lightGrayColor()
        self.view.addSubview(textField)

        currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
        currencyFormatter.currencyCode = NSLocale.currentLocale().displayNameForKey(NSLocaleCurrencySymbol, value: NSLocaleCurrencyCode)


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func textFieldDidChange(textField: UITextField) {
        var text = textField.text.stringByReplacingOccurrencesOfString(currencyFormatter.currencySymbol, withString: "").stringByReplacingOccurrencesOfString(currencyFormatter.groupingSeparator, withString: "").stringByReplacingOccurrencesOfString(currencyFormatter.decimalSeparator, withString: "")
        textField.text = currencyFormatter.stringFromNumber((text as NSString).doubleValue / 100.0)
    }

}

Let me know if you have questions.

Logan
  • 52,262
  • 20
  • 99
  • 128
  • Thanks. The code works perfectly for converting into currency format. Do you know how I can go about getting the result be shown in a label and to update as the user types? – user3746428 Jul 27 '14 at 03:06
  • @user3746428 - That should do it :) – Logan Jul 27 '14 at 03:46
  • Thank you! I'm currently building my first app and it's been going pretty smoothly but this has been an issue from the start, so I appreciate it! – user3746428 Jul 27 '14 at 03:54
  • I'm actually using this piece of code in two view controllers in my app and for some reason, one of them is working correctly and the other one isn't. The one that isn't working makes whatever text field is linked to the code disappear. I've tried placing a new text field and changing the code to work with that text field, but it just makes the new text field disappear and the other one reappears. Any ideas? – user3746428 Jul 27 '14 at 14:29
  • Hmm, not sure, I'd need more info to help with that one. This sounds like a new question, but if you link me, I'll take a look. – Logan Jul 27 '14 at 16:22
  • Yeah, it's pretty strange. Here is the question: http://stackoverflow.com/questions/24983622/textfield-disappears-when-formatted – user3746428 Jul 27 '14 at 17:34