DecimalTextField.swift 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. import SwiftUI
  2. struct DecimalTextField: UIViewRepresentable {
  3. private var placeholder: String
  4. @Binding var value: Decimal
  5. private var formatter: NumberFormatter
  6. private var autofocus: Bool
  7. private var cleanInput: Bool
  8. init(
  9. _ placeholder: String,
  10. value: Binding<Decimal>,
  11. formatter: NumberFormatter,
  12. autofocus: Bool = false,
  13. cleanInput: Bool = false
  14. ) {
  15. self.placeholder = placeholder
  16. _value = value
  17. self.formatter = formatter
  18. self.autofocus = autofocus
  19. self.cleanInput = cleanInput
  20. }
  21. func makeUIView(context: Context) -> UITextField {
  22. let textfield = UITextField()
  23. textfield.keyboardType = .decimalPad
  24. textfield.delegate = context.coordinator
  25. textfield.placeholder = placeholder
  26. textfield.text = cleanInput ? "" : formatter.string(for: value) ?? placeholder
  27. textfield.textAlignment = .right
  28. let toolBar = UIToolbar(frame: CGRect(
  29. x: 0,
  30. y: 0,
  31. width: textfield.frame.size.width,
  32. height: 44
  33. ))
  34. let clearButton = UIBarButtonItem(
  35. title: NSLocalizedString("Clear", comment: "Clear button"),
  36. style: .plain,
  37. target: self,
  38. action: #selector(textfield.clearButtonTapped(button:))
  39. )
  40. let doneButton = UIBarButtonItem(
  41. title: NSLocalizedString("Done", comment: "Done button"),
  42. style: .done,
  43. target: self,
  44. action: #selector(textfield.doneButtonTapped(button:))
  45. )
  46. let space = UIBarButtonItem(
  47. barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace,
  48. target: nil,
  49. action: nil
  50. )
  51. toolBar.setItems([clearButton, space, doneButton], animated: true)
  52. textfield.inputAccessoryView = toolBar
  53. if autofocus {
  54. DispatchQueue.main.async {
  55. textfield.becomeFirstResponder()
  56. }
  57. }
  58. return textfield
  59. }
  60. func updateUIView(_ textField: UITextField, context _: Context) {
  61. if value != 0 {
  62. textField.text = formatter.string(for: value)
  63. }
  64. }
  65. func makeCoordinator() -> Coordinator {
  66. Coordinator(self)
  67. }
  68. class Coordinator: NSObject, UITextFieldDelegate {
  69. var parent: DecimalTextField
  70. init(_ textField: DecimalTextField) {
  71. parent = textField
  72. }
  73. func textField(
  74. _ textField: UITextField,
  75. shouldChangeCharactersIn range: NSRange,
  76. replacementString string: String
  77. ) -> Bool {
  78. // Allow only numbers and decimal characters
  79. let isNumber = CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: string))
  80. let withDecimal = (
  81. string == NumberFormatter().decimalSeparator &&
  82. textField.text?.contains(string) == false
  83. )
  84. if isNumber || withDecimal,
  85. let currentValue = textField.text as NSString?
  86. {
  87. // Update Value
  88. let proposedValue = currentValue.replacingCharacters(in: range, with: string) as String
  89. let decimalFormatter = NumberFormatter()
  90. decimalFormatter.locale = Locale.current
  91. decimalFormatter.numberStyle = .decimal
  92. // Try currency formatter then Decimal formatrer
  93. let number = parent.formatter.number(from: proposedValue) ?? decimalFormatter.number(from: proposedValue) ?? 0.0
  94. // Set Value
  95. let double = number.doubleValue
  96. parent.value = Decimal(double)
  97. }
  98. return isNumber || withDecimal
  99. }
  100. func textFieldDidEndEditing(
  101. _ textField: UITextField,
  102. reason _: UITextField.DidEndEditingReason
  103. ) {
  104. // Format value with formatter at End Editing
  105. textField.text = parent.formatter.string(for: parent.value)
  106. }
  107. }
  108. }
  109. // MARK: extension for done button
  110. extension UITextField {
  111. @objc func doneButtonTapped(button _: UIBarButtonItem) {
  112. resignFirstResponder()
  113. }
  114. @objc func clearButtonTapped(button _: UIBarButtonItem) {
  115. text = ""
  116. }
  117. }
  118. // MARK: extension for keyboard to dismiss
  119. extension UIApplication {
  120. func endEditing() {
  121. sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
  122. }
  123. }