DecimalTextField.swift 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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: "Clear",
  36. style: .plain,
  37. target: self,
  38. action: #selector(textfield.clearButtonTapped(button:))
  39. )
  40. let doneButton = UIBarButtonItem(
  41. title: "Done",
  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(_: UITextField, context _: Context) {
  61. // textField.text = formatter.string(for: value)
  62. }
  63. func makeCoordinator() -> Coordinator {
  64. Coordinator(self)
  65. }
  66. class Coordinator: NSObject, UITextFieldDelegate {
  67. var parent: DecimalTextField
  68. init(_ textField: DecimalTextField) {
  69. parent = textField
  70. }
  71. func textField(
  72. _ textField: UITextField,
  73. shouldChangeCharactersIn range: NSRange,
  74. replacementString string: String
  75. ) -> Bool {
  76. // Allow only numbers and decimal characters
  77. let isNumber = CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: string))
  78. let withDecimal = (
  79. string == NumberFormatter().decimalSeparator &&
  80. textField.text?.contains(string) == false
  81. )
  82. if isNumber || withDecimal,
  83. let currentValue = textField.text as NSString?
  84. {
  85. // Update Value
  86. let proposedValue = currentValue.replacingCharacters(in: range, with: string) as String
  87. let decimalFormatter = NumberFormatter()
  88. decimalFormatter.locale = Locale.current
  89. decimalFormatter.numberStyle = .decimal
  90. // Try currency formatter then Decimal formatrer
  91. let number = parent.formatter.number(from: proposedValue) ?? decimalFormatter.number(from: proposedValue) ?? 0.0
  92. // Set Value
  93. let double = number.doubleValue
  94. parent.value = Decimal(double)
  95. }
  96. return isNumber || withDecimal
  97. }
  98. func textFieldDidEndEditing(
  99. _ textField: UITextField,
  100. reason _: UITextField.DidEndEditingReason
  101. ) {
  102. // Format value with formatter at End Editing
  103. textField.text = parent.formatter.string(for: parent.value)
  104. }
  105. }
  106. }
  107. // MARK: extension for done button
  108. extension UITextField {
  109. @objc func doneButtonTapped(button _: UIBarButtonItem) {
  110. resignFirstResponder()
  111. }
  112. @objc func clearButtonTapped(button _: UIBarButtonItem) {
  113. text = ""
  114. }
  115. }
  116. // MARK: extension for keyboard to dismiss
  117. extension UIApplication {
  118. func endEditing() {
  119. sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
  120. }
  121. }