DecimalTextField.swift 4.0 KB

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