DecimalTextField.swift 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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 = ""
  67. } else {
  68. textField.text = formatter.string(for: value)
  69. }
  70. }
  71. func makeCoordinator() -> Coordinator {
  72. Coordinator(self)
  73. }
  74. class Coordinator: NSObject, UITextFieldDelegate {
  75. var parent: DecimalTextField
  76. init(_ textField: DecimalTextField) {
  77. parent = textField
  78. }
  79. private(set) var isEditing = false
  80. private var editingCancellable: AnyCancellable?
  81. func resetEditing() {
  82. editingCancellable = Just(false)
  83. .delay(for: 0.5, scheduler: DispatchQueue.main)
  84. .weakAssign(to: \.isEditing, on: self)
  85. }
  86. func textField(
  87. _ textField: UITextField,
  88. shouldChangeCharactersIn range: NSRange,
  89. replacementString string: String
  90. ) -> Bool {
  91. // Allow only numbers and decimal characters
  92. let isNumber = CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: string))
  93. let withDecimal = (
  94. string == NumberFormatter().decimalSeparator &&
  95. textField.text?.contains(string) == false
  96. )
  97. if isNumber || withDecimal,
  98. let currentValue = textField.text as NSString?
  99. {
  100. // Update Value
  101. let proposedValue = currentValue.replacingCharacters(in: range, with: string) as String
  102. let decimalFormatter = NumberFormatter()
  103. decimalFormatter.locale = Locale.current
  104. decimalFormatter.numberStyle = .decimal
  105. // Try currency formatter then Decimal formatrer
  106. let number = parent.formatter.number(from: proposedValue) ?? decimalFormatter.number(from: proposedValue) ?? 0.0
  107. // Set Value
  108. let double = number.doubleValue
  109. isEditing = true
  110. parent.value = Decimal(double)
  111. }
  112. return isNumber || withDecimal
  113. }
  114. func textFieldDidEndEditing(
  115. _ textField: UITextField,
  116. reason _: UITextField.DidEndEditingReason
  117. ) {
  118. // Format value with formatter at End Editing
  119. textField.text = parent.formatter.string(for: parent.value)
  120. isEditing = false
  121. }
  122. }
  123. }
  124. // MARK: extension for done button
  125. extension UITextField {
  126. @objc func doneButtonTapped(button _: UIBarButtonItem) {
  127. resignFirstResponder()
  128. }
  129. @objc func clearButtonTapped(button _: UIBarButtonItem) {
  130. text = ""
  131. }
  132. }
  133. // MARK: extension for keyboard to dismiss
  134. extension UIApplication {
  135. func endEditing() {
  136. sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
  137. }
  138. }