Skip to content

Commit

Permalink
NumberSample - simplify format + fix modifying state during view update
Browse files Browse the repository at this point in the history
  • Loading branch information
popei69 committed Feb 27, 2022
1 parent ecacac9 commit 5c8378f
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions NumberSample/NumberSample/CurrencyUITextField.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,25 +45,31 @@ class CurrencyUITextField: UITextField {
@objc private func editingChanged() {
text = currency(from: decimal)
resetSelection()
value = Int(doubleValue * 100)
updateValue()
}

@objc private func resetSelection() {
selectedTextRange = textRange(from: endOfDocument, to: endOfDocument)
}

private var textValue: String {
return text ?? ""
private func updateValue() {
DispatchQueue.main.async {
self.value = self.intValue
}
}

private var doubleValue: Double {
return (decimal as NSDecimalNumber).doubleValue
private var textValue: String {
return text ?? ""
}

private var decimal: Decimal {
return textValue.decimal / pow(10, formatter.maximumFractionDigits)
}

private var intValue: Int {
return NSDecimalNumber(decimal: decimal * 100).intValue
}

private func currency(from decimal: Decimal) -> String {
return formatter.string(for: decimal) ?? ""
}
Expand Down

0 comments on commit 5c8378f

Please sign in to comment.