如何使用Swift在文本字段(从右到左)input货币格式?
我有一个数字让我们说0.00
。
- 当用户点击1时,我们应该有
0.01
- 当用户点击2.我们应该显示
0.12
- 当用户点击3.我们应该显示
1.23
- 当用户点击4.我们应该显示
12.34
我怎么能用Swift来做到这一点?
对于Swift 3 。 在文本字段上input货币格式(从右到左)
override func viewDidLoad() { super.viewDidLoad() textField.addTarget(self, action: #selector(myTextFieldDidChange), for: .editingChanged) } func myTextFieldDidChange(_ textField: UITextField) { if let amountString = textField.text?.currencyInputFormatting() { textField.text = amountString } } extension String { // formatting text for currency textField func currencyInputFormatting() -> String { var number: NSNumber! let formatter = NumberFormatter() formatter.numberStyle = .currencyAccounting formatter.currencySymbol = "$" formatter.maximumFractionDigits = 2 formatter.minimumFractionDigits = 2 var amountWithPrefix = self // remove from String: "$", ".", "," let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive) amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "") let double = (amountWithPrefix as NSString).doubleValue number = NSNumber(value: (double / 100)) // if first number is 0 or all numbers were deleted guard number != 0 as NSNumber else { return "" } return formatter.string(from: number)! } }
您可以创build一个货币文本字段inheritanceUITextField。 为UIControlEvents .editingChanged添加一个目标。 添加一个select器方法来过滤你的文本string中的数字。 在过滤掉string中的所有非数字后,您可以使用NumberFormatter再次格式化您的数字,如下所示:
Xcode 8.3.2•Swift 3.1
class CurrencyField: UITextField { var string: String { return text ?? "" } var decimal: Decimal { return string.digits.decimal / Decimal(pow(10, Double(Formatter.currency.maximumFractionDigits))) } var decimalNumber: NSDecimalNumber { return decimal.number } var doubleValue: Double { return decimalNumber.doubleValue } var integerValue: Int { return decimalNumber.intValue } let maximum: Decimal = 999_999_999.99 private var lastValue: String = "" override func willMove(toSuperview newSuperview: UIView?) { // you can make it a fixed locale currency if if needed // Formatter.currency.locale = Locale(identifier: "pt_BR") // or "en_US", "fr_FR", etc addTarget(self, action: #selector(editingChanged), for: .editingChanged) keyboardType = .numberPad textAlignment = .right editingChanged() } override func deleteBackward() { text = string.digits.dropLast().string editingChanged() } func editingChanged() { guard decimal <= maximum else { text = lastValue return } lastValue = Formatter.currency.string(for: decimal) ?? "" text = lastValue print("integer:", integerValue) print("double:", doubleValue) print("decimal:", decimal) print("currency:", lastValue) } }
extension NumberFormatter { convenience init(numberStyle: Style) { self.init() self.numberStyle = numberStyle } } extension Formatter { static let currency = NumberFormatter(numberStyle: .currency) } extension String { var digits: [UInt8] { return characters.flatMap{ UInt8(String($0)) } } } extension Collection where Iterator.Element == UInt8 { var string: String { return map(String.init).joined() } var decimal: Decimal { return Decimal(string: string) ?? 0 } } extension Decimal { var number: NSDecimalNumber { return NSDecimalNumber(decimal: self) } }
试试这段代码:
struct DotNum { private var fraction:String = "" private var intval:String = "" init() {} mutating func enter(s:String) { if count(fraction) < 2 { fraction = s + fraction } else { intval = s + intval } } private var sFract:String { if count(fraction) == 0 { return "00" } if count(fraction) == 1 { return "0\(fraction)" } return fraction } var stringVal:String { if intval == "" { return "0.\(sFract)" } return "\(intval).\(sFract)" } } var val = DotNum() val.enter("1") val.stringVal val.enter("2") val.stringVal val.enter("3") val.stringVal val.enter("4") val.stringVal
我最后的代码感谢您的帮助
extension Double { var twoDigits: Double { let nf = NSNumberFormatter() nf.numberStyle = NSNumberFormatterStyle.DecimalStyle nf.minimumFractionDigits = 2 nf.maximumFractionDigits = 2 return self } } var cleanText:String! let number:String = sender.currentTitle as String! if(amountDisplay.text != nil) { cleanText = String(Array(amountDisplay.text!).map{String($0)}.filter{ $0.toInt() != nil }.map{Character($0)} ) as String cleanText = cleanText + number }else{ cleanText = number } amount = (Double(cleanText.toInt()!) / 100).twoDigits formatter.locale = NSLocale(localeIdentifier: currencies[current_currency_index]) amountDisplay.text = "\(formatter.stringFromNumber(amount!)!)"