DecimalTextField.swift 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import Combine
  2. import SwiftUI
  3. struct DecimalTextField: UIViewRepresentable {
  4. private var placeholder: String
  5. @Binding var value: Decimal
  6. private var formatter: NumberFormatter
  7. private var autofocus: Bool
  8. private var cleanInput: Bool
  9. init(
  10. _ placeholder: String,
  11. value: Binding<Decimal>,
  12. formatter: NumberFormatter,
  13. autofocus: Bool = false,
  14. cleanInput: Bool = false
  15. ) {
  16. self.placeholder = placeholder
  17. _value = value
  18. self.formatter = formatter
  19. self.autofocus = autofocus
  20. self.cleanInput = cleanInput
  21. }
  22. func makeUIView(context: Context) -> UITextField {
  23. let textfield = UITextField()
  24. textfield.keyboardType = .decimalPad
  25. textfield.delegate = context.coordinator
  26. textfield.placeholder = placeholder
  27. textfield.text = cleanInput ? "" : formatter.string(for: value) ?? placeholder
  28. textfield.textAlignment = .right
  29. let toolBar = UIToolbar(frame: CGRect(
  30. x: 0,
  31. y: 0,
  32. width: textfield.frame.size.width,
  33. height: 44
  34. ))
  35. let clearButton = UIBarButtonItem(
  36. title: NSLocalizedString("Clear", comment: "Clear button"),
  37. style: .plain,
  38. target: self,
  39. action: #selector(textfield.clearButtonTapped(button:))
  40. )
  41. let doneButton = UIBarButtonItem(
  42. title: NSLocalizedString("Done", comment: "Done button"),
  43. style: .done,
  44. target: self,
  45. action: #selector(textfield.doneButtonTapped(button:))
  46. )
  47. let space = UIBarButtonItem(
  48. barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace,
  49. target: nil,
  50. action: nil
  51. )
  52. toolBar.setItems([clearButton, space, doneButton], animated: true)
  53. textfield.inputAccessoryView = toolBar
  54. if autofocus {
  55. DispatchQueue.main.async {
  56. textfield.becomeFirstResponder()
  57. }
  58. }
  59. return textfield
  60. }
  61. func updateUIView(_ textField: UITextField, context: Context) {
  62. let coordinator = context.coordinator
  63. if coordinator.isEditing {
  64. coordinator.resetEditing()
  65. } else if value != 0 {
  66. textField.text = formatter.string(for: value)
  67. }
  68. }
  69. func makeCoordinator() -> Coordinator {
  70. Coordinator(self)
  71. }
  72. class Coordinator: NSObject, UITextFieldDelegate {
  73. var parent: DecimalTextField
  74. init(_ textField: DecimalTextField) {
  75. parent = textField
  76. }
  77. private(set) var isEditing = false
  78. private var editingCancellable: AnyCancellable?
  79. func resetEditing() {
  80. editingCancellable = Just(false)
  81. .delay(for: 0.5, scheduler: DispatchQueue.main)
  82. .weakAssign(to: \.isEditing, on: self)
  83. }
  84. func textField(
  85. _ textField: UITextField,
  86. shouldChangeCharactersIn range: NSRange,
  87. replacementString string: String
  88. ) -> Bool {
  89. // Allow only numbers and decimal characters
  90. let isNumber = CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: string))
  91. let withDecimal = (
  92. string == NumberFormatter().decimalSeparator &&
  93. textField.text?.contains(string) == false
  94. )
  95. if isNumber || withDecimal,
  96. let currentValue = textField.text as NSString?
  97. {
  98. // Update Value
  99. let proposedValue = currentValue.replacingCharacters(in: range, with: string) as String
  100. let decimalFormatter = NumberFormatter()
  101. decimalFormatter.locale = Locale.current
  102. decimalFormatter.numberStyle = .decimal
  103. // Try currency formatter then Decimal formatrer
  104. let number = parent.formatter.number(from: proposedValue) ?? decimalFormatter.number(from: proposedValue) ?? 0.0
  105. // Set Value
  106. let double = number.doubleValue
  107. isEditing = true
  108. parent.value = Decimal(double)
  109. }
  110. return isNumber || withDecimal
  111. }
  112. func textFieldDidEndEditing(
  113. _ textField: UITextField,
  114. reason _: UITextField.DidEndEditingReason
  115. ) {
  116. // Format value with formatter at End Editing
  117. textField.text = parent.formatter.string(for: parent.value)
  118. isEditing = false
  119. }
  120. }
  121. }
  122. // MARK: extension for done button
  123. extension UITextField {
  124. @objc func doneButtonTapped(button _: UIBarButtonItem) {
  125. resignFirstResponder()
  126. }
  127. @objc func clearButtonTapped(button _: UIBarButtonItem) {
  128. text = ""
  129. }
  130. }
  131. // MARK: extension for keyboard to dismiss
  132. extension UIApplication {
  133. func endEditing() {
  134. sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
  135. }
  136. }