货币格式不起作用

时间:2014-09-10 15:28:20

标签: swift

我刚刚更新了Xcode 6的GM,我目前正在修复问题。

我的代码的某个特定部分存在问题,我一直在努力解决这个问题。基本上我以前有这个代码:

override func viewDidLoad() {
    currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
    currencyFormatter.currencyCode = NSLocale.currentLocale().displayNameForKey(NSLocaleCurrencySymbol, value: NSLocaleCurrencyCode)!
}

func textFieldDidChangeValue(textField: UITextField) {
    //Automatic formatting for transaction value text field. Target is added above.
    var text = textField.text.stringByReplacingOccurrencesOfString(currencyFormatter.currencySymbol, withString: "").stringByReplacingOccurrencesOfString(currencyFormatter.groupingSeparator, withString: "").stringByReplacingOccurrencesOfString(currencyFormatter.decimalSeparator, withString: "").stringByReplacingOccurrencesOfString(" ", withString: "") // There is a special character here. This line is critical for european/other currencies.
    println(textField.text)

    textField.text = currencyFormatter.stringFromNumber((text as NSString).doubleValue / 100.0)
    currencyDouble = (text as NSString).doubleValue / 100.0
    //println(currencyDouble)
    valueEnter.alpha = 100
}

我必须在我的应用崩溃时更改viewDidLoad()中的代码,以此:

let currencyFormatter = NSNumberFormatter()
    currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
    if let currencyCode = NSLocale.currentLocale().objectForKey(NSLocaleCurrencySymbol) as? String {
        currencyFormatter.currencyCode = currencyCode
        println(currencyFormatter.currencyCode) //Will display "$", for example, if your locale is set to USD
    }

应用程序不再崩溃,但格式化不起作用。我尝试了一些事情,但我还没有弄清楚如何修复它。

1 个答案:

答案 0 :(得分:1)

您使用currencyCode值设置NSLocaleCurrencySymbol。顾名思义,这就是错误的价值。正确的值为NSLocaleCurrencyCode