DecimalTextField.swift 5.4 KB

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