diff --git a/.gitignore b/.gitignore index ba1ff08..e27d315 100644 --- a/.gitignore +++ b/.gitignore @@ -87,4 +87,6 @@ fastlane/test_output # After new code Injection tools there's a generated folder /iOSInjectionProject # https://github.com/johnno1962/injectionforxcode -iOSInjectionProject/ \ No newline at end of file +iOSInjectionProject/ + +.DS_Store diff --git a/Sources/SwiftUIKit/views/CurrencyTextField.swift b/Sources/SwiftUIKit/views/CurrencyTextField.swift index 2352688..c26d68d 100644 --- a/Sources/SwiftUIKit/views/CurrencyTextField.swift +++ b/Sources/SwiftUIKit/views/CurrencyTextField.swift @@ -87,6 +87,11 @@ public struct CurrencyTextField: UIViewRepresentable { textField.addTarget(context.coordinator, action: #selector(context.coordinator.textFieldEditingDidBegin(_:)), for: .editingDidBegin) textField.addTarget(context.coordinator, action: #selector(context.coordinator.textFieldEditingDidEnd(_:)), for: .editingDidEnd) + // initial value + if let v = self.value { + textField.text = v.currencyFormat + } + // tag textField.tag = self.tag @@ -174,16 +179,7 @@ public struct CurrencyTextField: UIViewRepresentable { if self.value == nil { textField.text = nil } else { - // format to 2 decimal places if there's fractions - let formatter = Formatter.currency - var integer = 0.0 - let fraction = modf(self.value!, &integer) - if fraction > 0 { - formatter.maximumFractionDigits = 2 - } else { - formatter.maximumFractionDigits = 0 - } - textField.text = formatter.string(from: NSNumber(value: self.value!)) + textField.text = self.value!.currencyFormat } } @@ -306,6 +302,7 @@ public struct CurrencyTextField: UIViewRepresentable { } public func textFieldDidEndEditing(_ textField: UITextField) { + textField.text = self.value?.currencyFormat DispatchQueue.main.async { self.isResponder?.wrappedValue = false } @@ -404,6 +401,21 @@ fileprivate extension String { } } +fileprivate extension Double { + // format to 2 decimal places if there's fractions + var currencyFormat: String? { + let formatter = Formatter.currency + var integer = 0.0 + let fraction = modf(self, &integer) + if fraction > 0 { + formatter.maximumFractionDigits = 2 + } else { + formatter.maximumFractionDigits = 0 + } + return formatter.string(from: NSNumber(value: self)) + } +} + fileprivate struct Formatter { static let currency = NumberFormatter(numberStyle: .currency) } diff --git a/SwiftUIKitExampleApp/.DS_Store b/SwiftUIKitExampleApp/.DS_Store deleted file mode 100644 index 6c550bf..0000000 Binary files a/SwiftUIKitExampleApp/.DS_Store and /dev/null differ