TextFieldWithToolBar.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. var allowDecimalSeparator: Bool
  17. var previousTextField: (() -> Void)?
  18. var nextTextField: (() -> Void)?
  19. public init(
  20. text: Binding<Decimal>,
  21. placeholder: String,
  22. textColor: UIColor = .label,
  23. textAlignment: NSTextAlignment = .right,
  24. keyboardType: UIKeyboardType = .decimalPad,
  25. autocapitalizationType: UITextAutocapitalizationType = .none,
  26. autocorrectionType: UITextAutocorrectionType = .no,
  27. shouldBecomeFirstResponder: Bool = false,
  28. maxLength: Int? = nil,
  29. isDismissible: Bool = true,
  30. textFieldDidBeginEditing: (() -> Void)? = nil,
  31. numberFormatter: NumberFormatter,
  32. allowDecimalSeparator: Bool = true,
  33. previousTextField: (() -> Void)? = nil,
  34. nextTextField: (() -> Void)? = nil
  35. ) {
  36. _text = text
  37. self.placeholder = placeholder
  38. self.textColor = textColor
  39. self.textAlignment = textAlignment
  40. self.keyboardType = keyboardType
  41. self.autocapitalizationType = autocapitalizationType
  42. self.autocorrectionType = autocorrectionType
  43. self.shouldBecomeFirstResponder = shouldBecomeFirstResponder
  44. self.maxLength = maxLength
  45. self.isDismissible = isDismissible
  46. self.textFieldDidBeginEditing = textFieldDidBeginEditing
  47. self.numberFormatter = numberFormatter
  48. self.numberFormatter.numberStyle = .decimal
  49. self.allowDecimalSeparator = allowDecimalSeparator
  50. self.previousTextField = previousTextField
  51. self.nextTextField = nextTextField
  52. }
  53. public func makeUIView(context: Context) -> UITextField {
  54. let textField = UITextField()
  55. context.coordinator.textField = textField
  56. textField.inputAccessoryView = isDismissible ? makeDoneToolbar(for: textField, context: context) : nil
  57. textField.addTarget(context.coordinator, action: #selector(Coordinator.editingDidBegin), for: .editingDidBegin)
  58. textField.delegate = context.coordinator
  59. if text == 0 { /// show no value initially, i.e. empty String
  60. textField.text = ""
  61. } else {
  62. textField.text = numberFormatter.string(for: text)
  63. }
  64. textField.placeholder = placeholder
  65. return textField
  66. }
  67. private func makeDoneToolbar(for textField: UITextField, context: Context) -> UIToolbar {
  68. let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
  69. let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
  70. let doneButton = UIBarButtonItem(
  71. image: UIImage(systemName: "keyboard.chevron.compact.down"),
  72. style: .done,
  73. target: textField,
  74. action: #selector(UITextField.resignFirstResponder)
  75. )
  76. let clearButton = UIBarButtonItem(
  77. image: UIImage(systemName: "trash"),
  78. style: .plain,
  79. target: context.coordinator,
  80. action: #selector(Coordinator.clearText)
  81. )
  82. let previousButton = UIBarButtonItem(
  83. image: UIImage(systemName: "chevron.up"),
  84. style: .plain,
  85. target: context.coordinator,
  86. action: #selector(Coordinator.previousTextField)
  87. )
  88. let nextButton = UIBarButtonItem(
  89. image: UIImage(systemName: "chevron.down"),
  90. style: .plain,
  91. target: context.coordinator,
  92. action: #selector(Coordinator.nextTextField)
  93. )
  94. toolbar.items = [clearButton, previousButton, nextButton, flexibleSpace, doneButton]
  95. toolbar.sizeToFit()
  96. return toolbar
  97. }
  98. public func updateUIView(_ textField: UITextField, context: Context) {
  99. if text != 0 {
  100. let newText = numberFormatter.string(for: text) ?? ""
  101. if textField.text != newText {
  102. textField.text = newText
  103. }
  104. }
  105. textField.textColor = textColor
  106. textField.textAlignment = textAlignment
  107. textField.keyboardType = keyboardType
  108. textField.autocapitalizationType = autocapitalizationType
  109. textField.autocorrectionType = autocorrectionType
  110. if shouldBecomeFirstResponder, !context.coordinator.didBecomeFirstResponder {
  111. if textField.window != nil, textField.becomeFirstResponder() {
  112. context.coordinator.didBecomeFirstResponder = true
  113. }
  114. } else if !shouldBecomeFirstResponder, context.coordinator.didBecomeFirstResponder {
  115. context.coordinator.didBecomeFirstResponder = false
  116. }
  117. }
  118. public func makeCoordinator() -> Coordinator {
  119. Coordinator(self, maxLength: maxLength)
  120. }
  121. public final class Coordinator: NSObject {
  122. var parent: TextFieldWithToolBar
  123. var textField: UITextField?
  124. let maxLength: Int?
  125. var didBecomeFirstResponder = false
  126. let decimalFormatter: NumberFormatter
  127. init(_ parent: TextFieldWithToolBar, maxLength: Int?) {
  128. self.parent = parent
  129. self.maxLength = maxLength
  130. decimalFormatter = NumberFormatter()
  131. decimalFormatter.locale = Locale.current
  132. decimalFormatter.numberStyle = .decimal
  133. }
  134. @objc fileprivate func clearText() {
  135. parent.text = 0
  136. textField?.text = ""
  137. }
  138. @objc fileprivate func editingDidBegin(_ textField: UITextField) {
  139. DispatchQueue.main.async {
  140. textField.moveCursorToEnd()
  141. }
  142. }
  143. @objc fileprivate func previousTextField() {
  144. parent.previousTextField?()
  145. }
  146. @objc fileprivate func nextTextField() {
  147. parent.nextTextField?()
  148. }
  149. // Helper method to calculate the number of decimal places in a string
  150. fileprivate func calculateDecimalPlaces(in string: String) -> Int {
  151. guard let decimalSeparator = decimalFormatter.decimalSeparator else { return 0 }
  152. if let range = string.range(of: decimalSeparator) {
  153. let decimalPart = string[range.upperBound...]
  154. return decimalPart.count
  155. }
  156. return 0
  157. }
  158. // Helper method to check if the cursor is after the decimal separator
  159. fileprivate func isCursorAfterDecimal(in textField: UITextField, range: NSRange) -> Bool {
  160. guard let text = textField.text, let decimalSeparator = decimalFormatter.decimalSeparator else { return false }
  161. if let decimalSeparatorRange = text.range(of: decimalSeparator) {
  162. let decimalSeparatorPosition = text.distance(from: text.startIndex, to: decimalSeparatorRange.lowerBound)
  163. return range.location > decimalSeparatorPosition
  164. }
  165. return false
  166. }
  167. }
  168. }
  169. extension TextFieldWithToolBar.Coordinator: UITextFieldDelegate {
  170. public func textField(
  171. _ textField: UITextField,
  172. shouldChangeCharactersIn range: NSRange,
  173. replacementString string: String
  174. ) -> Bool {
  175. // Check if the input is a number or the decimal separator
  176. let isNumber = CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: string))
  177. let isDecimalSeparator = (string == decimalFormatter.decimalSeparator && textField.text?.contains(string) == false)
  178. // Only proceed if the input is a valid number or decimal separator
  179. if isNumber || isDecimalSeparator && parent.allowDecimalSeparator,
  180. let currentText = textField.text as NSString?
  181. {
  182. // Get the proposed new text
  183. let proposedTextOriginal = currentText.replacingCharacters(in: range, with: string)
  184. // Remove thousand separator
  185. let proposedText = proposedTextOriginal.replacingOccurrences(of: decimalFormatter.groupingSeparator, with: "")
  186. // Try to convert proposed text to number
  187. let number = parent.numberFormatter.number(from: proposedText) ?? decimalFormatter.number(from: proposedText)
  188. let decimalPlacesCurrent = calculateDecimalPlaces(in: currentText as String)
  189. let maxDecimalPlaces = parent.numberFormatter.maximumFractionDigits
  190. let isCursorAfterDecimal = isCursorAfterDecimal(in: textField, range: range)
  191. if decimalPlacesCurrent >= maxDecimalPlaces,
  192. range.length == 0,
  193. isCursorAfterDecimal
  194. {
  195. return false
  196. }
  197. // Update the binding value if conversion is successful
  198. if let number = number {
  199. let lastCharIndex = proposedText.index(before: proposedText.endIndex)
  200. let hasDecimalSeparator = proposedText.contains(decimalFormatter.decimalSeparator)
  201. let hasTrailingZeros = (hasDecimalSeparator && proposedText[lastCharIndex] == "0") || isDecimalSeparator
  202. if !hasTrailingZeros
  203. {
  204. parent.text = number.decimalValue
  205. }
  206. } else {
  207. parent.text = 0
  208. }
  209. }
  210. // Allow the change if it's a valid number or decimal separator
  211. return isNumber || isDecimalSeparator && parent.allowDecimalSeparator
  212. }
  213. public func textFieldDidBeginEditing(_: UITextField) {
  214. parent.textFieldDidBeginEditing?()
  215. }
  216. }
  217. extension UITextField {
  218. func moveCursorToEnd() {
  219. dispatchPrecondition(condition: .onQueue(.main))
  220. let newPosition = endOfDocument
  221. selectedTextRange = textRange(from: newPosition, to: newPosition)
  222. }
  223. }
  224. extension UIApplication {
  225. func endEditing() {
  226. sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
  227. }
  228. }
  229. public struct TextFieldWithToolBarString: UIViewRepresentable {
  230. @Binding var text: String
  231. var placeholder: String
  232. var textAlignment: NSTextAlignment = .right
  233. var keyboardType: UIKeyboardType = .default
  234. var autocapitalizationType: UITextAutocapitalizationType = .none
  235. var autocorrectionType: UITextAutocorrectionType = .no
  236. var shouldBecomeFirstResponder: Bool = false
  237. var maxLength: Int? = nil
  238. var isDismissible: Bool = true
  239. public func makeUIView(context: Context) -> UITextField {
  240. let textField = UITextField()
  241. context.coordinator.textField = textField
  242. textField.inputAccessoryView = isDismissible ? makeDoneToolbar(for: textField, context: context) : nil
  243. textField.addTarget(context.coordinator, action: #selector(Coordinator.editingDidBegin), for: .editingDidBegin)
  244. textField.delegate = context.coordinator
  245. textField.text = text
  246. textField.placeholder = placeholder
  247. textField.textAlignment = textAlignment
  248. textField.keyboardType = keyboardType
  249. textField.autocapitalizationType = autocapitalizationType
  250. textField.autocorrectionType = autocorrectionType
  251. textField.adjustsFontSizeToFitWidth = true
  252. return textField
  253. }
  254. private func makeDoneToolbar(for textField: UITextField, context: Context) -> UIToolbar {
  255. let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
  256. let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
  257. let doneButton = UIBarButtonItem(
  258. image: UIImage(systemName: "keyboard.chevron.compact.down"),
  259. style: .done,
  260. target: textField,
  261. action: #selector(UITextField.resignFirstResponder)
  262. )
  263. let clearButton = UIBarButtonItem(
  264. image: UIImage(systemName: "trash"),
  265. style: .plain,
  266. target: context.coordinator,
  267. action: #selector(Coordinator.clearText)
  268. )
  269. toolbar.items = [clearButton, flexibleSpace, doneButton]
  270. toolbar.sizeToFit()
  271. return toolbar
  272. }
  273. public func updateUIView(_ textField: UITextField, context: Context) {
  274. if textField.text != text {
  275. textField.text = text
  276. }
  277. textField.textAlignment = textAlignment
  278. textField.keyboardType = keyboardType
  279. textField.autocapitalizationType = autocapitalizationType
  280. textField.autocorrectionType = autocorrectionType
  281. if shouldBecomeFirstResponder, !context.coordinator.didBecomeFirstResponder {
  282. if textField.window != nil, textField.becomeFirstResponder() {
  283. context.coordinator.didBecomeFirstResponder = true
  284. }
  285. } else if !shouldBecomeFirstResponder, context.coordinator.didBecomeFirstResponder {
  286. context.coordinator.didBecomeFirstResponder = false
  287. }
  288. }
  289. public func makeCoordinator() -> Coordinator {
  290. Coordinator(self, maxLength: maxLength)
  291. }
  292. public final class Coordinator: NSObject {
  293. var parent: TextFieldWithToolBarString
  294. var textField: UITextField?
  295. let maxLength: Int?
  296. var didBecomeFirstResponder = false
  297. init(_ parent: TextFieldWithToolBarString, maxLength: Int?) {
  298. self.parent = parent
  299. self.maxLength = maxLength
  300. }
  301. @objc fileprivate func clearText() {
  302. parent.text = ""
  303. textField?.text = ""
  304. }
  305. @objc fileprivate func editingDidBegin(_ textField: UITextField) {
  306. DispatchQueue.main.async {
  307. textField.moveCursorToEnd()
  308. }
  309. }
  310. }
  311. }
  312. extension TextFieldWithToolBarString.Coordinator: UITextFieldDelegate {
  313. public func textField(
  314. _ textField: UITextField,
  315. shouldChangeCharactersIn range: NSRange,
  316. replacementString string: String
  317. ) -> Bool {
  318. guard let currentText = textField.text as NSString? else {
  319. return false
  320. }
  321. // Calculate the new text length
  322. let newLength = currentText.length + string.count - range.length
  323. // If there's a maxLength, ensure the new length is within the limit
  324. if let maxLength = parent.maxLength, newLength > maxLength {
  325. return false
  326. }
  327. // Attempt to replace characters in range with the replacement string
  328. let newText = currentText.replacingCharacters(in: range, with: string)
  329. // Update the binding text state
  330. DispatchQueue.main.async {
  331. self.parent.text = newText
  332. }
  333. return true
  334. }
  335. }