Skip to content

Commit

Permalink
fix: issue #11
Browse files Browse the repository at this point in the history
  • Loading branch information
youjinp committed Sep 26, 2020
1 parent 572d0f4 commit e7c19e6
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 11 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Expand Up @@ -87,4 +87,6 @@ fastlane/test_output
# After new code Injection tools there's a generated folder /iOSInjectionProject
# https://github.com/johnno1962/injectionforxcode

iOSInjectionProject/
iOSInjectionProject/

.DS_Store
32 changes: 22 additions & 10 deletions Sources/SwiftUIKit/views/CurrencyTextField.swift
Expand Up @@ -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

Expand Down Expand Up @@ -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
}
}

Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
}
Expand Down
Binary file removed SwiftUIKitExampleApp/.DS_Store
Binary file not shown.

0 comments on commit e7c19e6

Please sign in to comment.