DecimalTextField.swift 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import SwiftUI
  2. import UIKit
  3. public struct TextFieldWithToolBar: UIViewRepresentable {
  4. @Binding var text: Decimal
  5. var placeholder: String
  6. var textColor: UIColor
  7. var textAlignment: NSTextAlignment
  8. var keyboardType: UIKeyboardType
  9. var autocapitalizationType: UITextAutocapitalizationType
  10. var autocorrectionType: UITextAutocorrectionType
  11. var shouldBecomeFirstResponder: Bool
  12. var maxLength: Int?
  13. var isDismissible: Bool
  14. var textFieldDidBeginEditing: (() -> Void)?
  15. var numberFormatter: NumberFormatter
  16. public init(
  17. text: Binding<Decimal>,
  18. placeholder: String,
  19. textColor: UIColor = .label,
  20. textAlignment: NSTextAlignment = .right,
  21. keyboardType: UIKeyboardType = .decimalPad,
  22. autocapitalizationType: UITextAutocapitalizationType = .none,
  23. autocorrectionType: UITextAutocorrectionType = .no,
  24. shouldBecomeFirstResponder: Bool = false,
  25. maxLength: Int? = nil,
  26. isDismissible: Bool = true,
  27. textFieldDidBeginEditing: (() -> Void)? = nil,
  28. numberFormatter: NumberFormatter
  29. ) {
  30. _text = text
  31. self.placeholder = placeholder
  32. self.textColor = textColor
  33. self.textAlignment = textAlignment
  34. self.keyboardType = keyboardType
  35. self.autocapitalizationType = autocapitalizationType
  36. self.autocorrectionType = autocorrectionType
  37. self.shouldBecomeFirstResponder = shouldBecomeFirstResponder
  38. self.maxLength = maxLength
  39. self.isDismissible = isDismissible
  40. self.textFieldDidBeginEditing = textFieldDidBeginEditing
  41. self.numberFormatter = numberFormatter
  42. self.numberFormatter.numberStyle = .decimal
  43. }
  44. public func makeUIView(context: Context) -> UITextField {
  45. let textField = UITextField()
  46. context.coordinator.textField = textField
  47. textField.inputAccessoryView = isDismissible ? makeDoneToolbar(for: textField, context: context) : nil
  48. textField.addTarget(context.coordinator, action: #selector(Coordinator.editingDidBegin), for: .editingDidBegin)
  49. textField.delegate = context.coordinator
  50. if text == 0 { /// show no value initially, i.e. empty String
  51. textField.text = ""
  52. } else {
  53. textField.text = numberFormatter.string(for: text)
  54. }
  55. textField.placeholder = placeholder
  56. return textField
  57. }
  58. private func makeDoneToolbar(for textField: UITextField, context: Context) -> UIToolbar {
  59. let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
  60. let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
  61. let doneButton = UIBarButtonItem(
  62. image: UIImage(systemName: "keyboard.chevron.compact.down"),
  63. style: .done,
  64. target: textField,
  65. action: #selector(UITextField.resignFirstResponder)
  66. )
  67. let clearButton = UIBarButtonItem(
  68. image: UIImage(systemName: "trash"),
  69. style: .plain,
  70. target: context.coordinator,
  71. action: #selector(Coordinator.clearText)
  72. )
  73. toolbar.items = [clearButton, flexibleSpace, doneButton]
  74. toolbar.sizeToFit()
  75. return toolbar
  76. }
  77. public func updateUIView(_ textField: UITextField, context: Context) {
  78. if textField.isFirstResponder {
  79. return
  80. }
  81. if text != 0 {
  82. let newText = numberFormatter.string(for: text) ?? ""
  83. if textField.text != newText {
  84. textField.text = newText
  85. }
  86. }
  87. textField.textColor = textColor
  88. textField.textAlignment = textAlignment
  89. textField.keyboardType = keyboardType
  90. textField.autocapitalizationType = autocapitalizationType
  91. textField.autocorrectionType = autocorrectionType
  92. if shouldBecomeFirstResponder, !context.coordinator.didBecomeFirstResponder {
  93. if textField.window != nil, textField.becomeFirstResponder() {
  94. context.coordinator.didBecomeFirstResponder = true
  95. }
  96. } else if !shouldBecomeFirstResponder, context.coordinator.didBecomeFirstResponder {
  97. context.coordinator.didBecomeFirstResponder = false
  98. }
  99. }
  100. public func makeCoordinator() -> Coordinator {
  101. Coordinator(self, maxLength: maxLength)
  102. }
  103. public final class Coordinator: NSObject {
  104. var parent: TextFieldWithToolBar
  105. var textField: UITextField?
  106. let maxLength: Int?
  107. var didBecomeFirstResponder = false
  108. let decimalFormatter: NumberFormatter
  109. init(_ parent: TextFieldWithToolBar, maxLength: Int?) {
  110. self.parent = parent
  111. self.maxLength = maxLength
  112. decimalFormatter = NumberFormatter()
  113. decimalFormatter.locale = Locale.current
  114. decimalFormatter.numberStyle = .decimal
  115. }
  116. @objc fileprivate func clearText() {
  117. parent.text = 0
  118. textField?.text = ""
  119. }
  120. @objc fileprivate func editingDidBegin(_ textField: UITextField) {
  121. DispatchQueue.main.async {
  122. textField.moveCursorToEnd()
  123. }
  124. }
  125. }
  126. }
  127. extension TextFieldWithToolBar.Coordinator: UITextFieldDelegate {
  128. public func textField(
  129. _ textField: UITextField,
  130. shouldChangeCharactersIn range: NSRange,
  131. replacementString string: String
  132. ) -> Bool {
  133. // Check if the input is a number or the decimal separator
  134. let isNumber = CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: string))
  135. let isDecimalSeparator = (string == decimalFormatter.decimalSeparator && textField.text?.contains(string) == false)
  136. // Only proceed if the input is a valid number or decimal separator
  137. if isNumber || isDecimalSeparator,
  138. let currentText = textField.text as NSString?
  139. {
  140. // Get the proposed new text
  141. let proposedText = currentText.replacingCharacters(in: range, with: string)
  142. // Try to convert proposed text to number
  143. let number = parent.numberFormatter.number(from: proposedText) ?? decimalFormatter.number(from: proposedText)
  144. // Update the binding value if conversion is successful
  145. if let number = number {
  146. parent.text = number.decimalValue
  147. } else {
  148. parent.text = 0
  149. }
  150. }
  151. // Allow the change if it's a valid number or decimal separator
  152. return isNumber || isDecimalSeparator
  153. }
  154. public func textFieldDidBeginEditing(_: UITextField) {
  155. parent.textFieldDidBeginEditing?()
  156. }
  157. }
  158. extension UITextField {
  159. func moveCursorToEnd() {
  160. dispatchPrecondition(condition: .onQueue(.main))
  161. let newPosition = endOfDocument
  162. selectedTextRange = textRange(from: newPosition, to: newPosition)
  163. }
  164. }
  165. extension UIApplication {
  166. func endEditing() {
  167. sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
  168. }
  169. }