From 75a7f5642b481d3635740b960a1f43b38fa0df44 Mon Sep 17 00:00:00 2001 From: Deniz Cengiz <48965855+dnzxy@users.noreply.github.com> Date: Sat, 27 Jul 2024 02:12:12 +0200 Subject: [PATCH] Merge pull request #352 from MikePlante1/deleting_meal_note_fix Prevent crash when holding backspace --- .../Sources/Views/TextFieldWithToolBar.swift | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/FreeAPS/Sources/Views/TextFieldWithToolBar.swift b/FreeAPS/Sources/Views/TextFieldWithToolBar.swift index 2095d8537..67ce897d8 100644 --- a/FreeAPS/Sources/Views/TextFieldWithToolBar.swift +++ b/FreeAPS/Sources/Views/TextFieldWithToolBar.swift @@ -290,20 +290,24 @@ extension TextFieldWithToolBarString.Coordinator: UITextFieldDelegate { shouldChangeCharactersIn range: NSRange, replacementString string: String ) -> Bool { - if let maxLength = parent.maxLength { - // Get the current text, including the proposed change - let currentText = textField.text ?? "" - let newLength = currentText.count + string.count - range.length - if newLength > maxLength { - return false - } + guard let currentText = textField.text as NSString? else { + return false + } + + // Calculate the new text length + let newLength = currentText.length + string.count - range.length + + // If there's a maxLength, ensure the new length is within the limit + if let maxLength = parent.maxLength, newLength > maxLength { + return false } + // Attempt to replace characters in range with the replacement string + let newText = currentText.replacingCharacters(in: range, with: string) + + // Update the binding text state DispatchQueue.main.async { - if let textFieldText = textField.text as NSString? { - let newText = textFieldText.replacingCharacters(in: range, with: string) - self.parent.text = newText - } + self.parent.text = newText } return true