DecimalTextField.swift 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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. if autofocus {
  30. DispatchQueue.main.async {
  31. textfield.becomeFirstResponder()
  32. }
  33. }
  34. return textfield
  35. }
  36. func updateUIView(_ textField: UITextField, context: Context) {
  37. let coordinator = context.coordinator
  38. if coordinator.isEditing {
  39. coordinator.resetEditing()
  40. } else if value == 0 {
  41. textField.text = ""
  42. } else {
  43. textField.text = formatter.string(for: value)
  44. }
  45. }
  46. func makeCoordinator() -> Coordinator {
  47. Coordinator(self)
  48. }
  49. class Coordinator: NSObject, UITextFieldDelegate {
  50. var parent: DecimalTextField
  51. init(_ textField: DecimalTextField) {
  52. parent = textField
  53. }
  54. private(set) var isEditing = false
  55. private var editingCancellable: AnyCancellable?
  56. func resetEditing() {
  57. editingCancellable = Just(false)
  58. .delay(for: 0.5, scheduler: DispatchQueue.main)
  59. .weakAssign(to: \.isEditing, on: self)
  60. }
  61. func textField(
  62. _ textField: UITextField,
  63. shouldChangeCharactersIn range: NSRange,
  64. replacementString string: String
  65. ) -> Bool {
  66. // Allow only numbers and decimal characters
  67. let isNumber = CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: string))
  68. let withDecimal = (
  69. string == NumberFormatter().decimalSeparator &&
  70. textField.text?.contains(string) == false
  71. )
  72. if isNumber || withDecimal,
  73. let currentValue = textField.text as NSString?
  74. {
  75. // Update Value
  76. let proposedValue = currentValue.replacingCharacters(in: range, with: string) as String
  77. let decimalFormatter = NumberFormatter()
  78. decimalFormatter.locale = Locale.current
  79. decimalFormatter.numberStyle = .decimal
  80. // Try currency formatter then Decimal formatrer
  81. let number = parent.formatter.number(from: proposedValue) ?? decimalFormatter.number(from: proposedValue) ?? 0.0
  82. // Set Value
  83. let double = number.doubleValue
  84. isEditing = true
  85. parent.value = Decimal(double)
  86. }
  87. return isNumber || withDecimal
  88. }
  89. func textFieldDidEndEditing(
  90. _ textField: UITextField,
  91. reason _: UITextField.DidEndEditingReason
  92. ) {
  93. // Format value with formatter at End Editing
  94. textField.text = parent.formatter.string(for: parent.value)
  95. isEditing = false
  96. }
  97. }
  98. }
  99. // MARK: extension for done button
  100. extension UITextField {
  101. @objc func doneButtonTapped(button _: UIBarButtonItem) {
  102. resignFirstResponder()
  103. }
  104. @objc func clearButtonTapped(button _: UIBarButtonItem) {
  105. text = ""
  106. }
  107. }
  108. // MARK: extension for keyboard to dismiss
  109. extension UIApplication {
  110. func endEditing() {
  111. sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
  112. }
  113. }