DecimalTextField.swift 5.2 KB

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