我试图在
Swift的文本字段中格式化货币输入,用户输入它.
到目前为止,我只能在用户完成输入时成功格式化:
@IBAction func editingEnded(sender: AnyObject) { let formatter = NSNumberFormatter() formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle formatter.locale = NSLocale(localeIdentifier: "en_US") var numberFromField = NSString(string: textField.text).doubleValue textField.text = formatter.stringFromNumber(numberFromField) }
但是,我希望货币在用户输入时被格式化.当我尝试在TextField操作“编辑更改”或“更改值”时,只能输入1个数字(如果输入8,则变为$8.00),但是一旦输入第二个数字,所有内容都将转到$0.00,而I不能进一步超越这一点.
有什么建议么?我觉得这应该是一个简单的修复,但我不能完全了解它.
解决方法
我修改了今天早些时候的功能.适用于“en_US”和“fr_FR”.然而,对于“ja_JP”,除以100我做创建小数是一个问题.您将需要一个开关或if / else语句来分隔货币与小数和没有格式化格式化程序的货币.但我认为这可以让你在你想成为的空间.
import UIKit class ViewController: UIViewController,UITextFieldDelegate { @IBOutlet weak var textField: UITextField! var currentString = "" override func viewDidLoad() { super.viewDidLoad() self.textField.delegate = self } //Textfield delegates func textField(textField: UITextField,shouldChangeCharactersInRange range: NSRange,replacementString string: String) -> Bool { // return NO to not change text switch string { case "0","1","2","3","4","5","6","7","8","9": currentString += string println(currentString) formatCurrency(string: currentString) default: var array = Array(string) var currentStringArray = Array(currentString) if array.count == 0 && currentStringArray.count != 0 { currentStringArray.removeLast() currentString = "" for character in currentStringArray { currentString += String(character) } formatCurrency(string: currentString) } } return false } func formatCurrency(#string: String) { println("format \(string)") let formatter = NSNumberFormatter() formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle formatter.locale = NSLocale(localeIdentifier: "en_US") var numberFromField = (NSString(string: currentString).doubleValue)/100 textField.text = formatter.stringFromNumber(numberFromField) println(textField.text ) } }