TextFieldWithToolBar.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. DispatchQueue.main.async {
  205. self.parent.text = number.decimalValue
  206. }
  207. }
  208. } else {
  209. DispatchQueue.main.async {
  210. self.parent.text = 0
  211. }
  212. }
  213. }
  214. // Allow the change if it's a valid number or decimal separator
  215. return isNumber || isDecimalSeparator && parent.allowDecimalSeparator
  216. }
  217. public func textFieldDidBeginEditing(_: UITextField) {
  218. parent.textFieldDidBeginEditing?()
  219. }
  220. }
  221. extension UITextField {
  222. func moveCursorToEnd() {
  223. dispatchPrecondition(condition: .onQueue(.main))
  224. let newPosition = endOfDocument
  225. selectedTextRange = textRange(from: newPosition, to: newPosition)
  226. }
  227. }
  228. extension UIApplication {
  229. func endEditing() {
  230. sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
  231. }
  232. }
  233. public struct TextFieldWithToolBarString: UIViewRepresentable {
  234. @Binding var text: String
  235. var placeholder: String
  236. var textAlignment: NSTextAlignment = .right
  237. var keyboardType: UIKeyboardType = .default
  238. var autocapitalizationType: UITextAutocapitalizationType = .none
  239. var autocorrectionType: UITextAutocorrectionType = .no
  240. var shouldBecomeFirstResponder: Bool = false
  241. var maxLength: Int? = nil
  242. var isDismissible: Bool = true
  243. public func makeUIView(context: Context) -> UITextField {
  244. let textField = UITextField()
  245. context.coordinator.textField = textField
  246. textField.inputAccessoryView = isDismissible ? makeDoneToolbar(for: textField, context: context) : nil
  247. textField.addTarget(context.coordinator, action: #selector(Coordinator.editingDidBegin), for: .editingDidBegin)
  248. textField.delegate = context.coordinator
  249. textField.text = text
  250. textField.placeholder = placeholder
  251. textField.textAlignment = textAlignment
  252. textField.keyboardType = keyboardType
  253. textField.autocapitalizationType = autocapitalizationType
  254. textField.autocorrectionType = autocorrectionType
  255. textField.adjustsFontSizeToFitWidth = true
  256. return textField
  257. }
  258. private func makeDoneToolbar(for textField: UITextField, context: Context) -> UIToolbar {
  259. let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
  260. let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
  261. let doneButton = UIBarButtonItem(
  262. image: UIImage(systemName: "keyboard.chevron.compact.down"),
  263. style: .done,
  264. target: textField,
  265. action: #selector(UITextField.resignFirstResponder)
  266. )
  267. let clearButton = UIBarButtonItem(
  268. image: UIImage(systemName: "trash"),
  269. style: .plain,
  270. target: context.coordinator,
  271. action: #selector(Coordinator.clearText)
  272. )
  273. toolbar.items = [clearButton, flexibleSpace, doneButton]
  274. toolbar.sizeToFit()
  275. return toolbar
  276. }
  277. public func updateUIView(_ textField: UITextField, context: Context) {
  278. if textField.text != text {
  279. textField.text = text
  280. }
  281. textField.textAlignment = textAlignment
  282. textField.keyboardType = keyboardType
  283. textField.autocapitalizationType = autocapitalizationType
  284. textField.autocorrectionType = autocorrectionType
  285. if shouldBecomeFirstResponder, !context.coordinator.didBecomeFirstResponder {
  286. if textField.window != nil, textField.becomeFirstResponder() {
  287. context.coordinator.didBecomeFirstResponder = true
  288. }
  289. } else if !shouldBecomeFirstResponder, context.coordinator.didBecomeFirstResponder {
  290. context.coordinator.didBecomeFirstResponder = false
  291. }
  292. }
  293. public func makeCoordinator() -> Coordinator {
  294. Coordinator(self, maxLength: maxLength)
  295. }
  296. public final class Coordinator: NSObject {
  297. var parent: TextFieldWithToolBarString
  298. var textField: UITextField?
  299. let maxLength: Int?
  300. var didBecomeFirstResponder = false
  301. init(_ parent: TextFieldWithToolBarString, maxLength: Int?) {
  302. self.parent = parent
  303. self.maxLength = maxLength
  304. }
  305. @objc fileprivate func clearText() {
  306. parent.text = ""
  307. textField?.text = ""
  308. }
  309. @objc fileprivate func editingDidBegin(_ textField: UITextField) {
  310. DispatchQueue.main.async {
  311. textField.moveCursorToEnd()
  312. }
  313. }
  314. }
  315. }
  316. extension TextFieldWithToolBarString.Coordinator: UITextFieldDelegate {
  317. public func textField(
  318. _ textField: UITextField,
  319. shouldChangeCharactersIn range: NSRange,
  320. replacementString string: String
  321. ) -> Bool {
  322. guard let currentText = textField.text as NSString? else {
  323. return false
  324. }
  325. // Calculate the new text length
  326. let newLength = currentText.length + string.count - range.length
  327. // If there's a maxLength, ensure the new length is within the limit
  328. if let maxLength = parent.maxLength, newLength > maxLength {
  329. return false
  330. }
  331. // Attempt to replace characters in range with the replacement string
  332. let newText = currentText.replacingCharacters(in: range, with: string)
  333. // Update the binding text state
  334. DispatchQueue.main.async {
  335. self.parent.text = newText
  336. }
  337. return true
  338. }
  339. }