-1

i want to remove one last character when user presses the backspace


        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

            if string.isEmpty {
                print("backspace pressed")

                if let itemToRemove = textField.text?.dropLast(){
                  let text = textField.text?.replacingOccurrences(of: itemToRemove, with: "")
                    textField.text = text
                    return true
                }
            }
            return true
        }

this function clears all the elements present in the textfield

Wahid Tariq
  • 159
  • 10
  • The easiest way to accomplish that is to subclass `UITextField` and override deleteBackward method. Then you can decide which behavior that method will have. – Leo Dabus Apr 04 '22 at 13:57

2 Answers2

1
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            
            // Backspace handled
            guard !string.isEmpty else {
                return true
            }
            
            return true
        }
Wahid Tariq
  • 159
  • 10
  • [A code-only answer is not high quality](//meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers). While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please [edit] your answer to include explanation and link to relevant documentation. – Muhammad Mohsin Khan Apr 05 '22 at 08:46
0

You're using this method wrong. The delegate method is not for you to implement the change to the text, it's for you to approve the change (hence returning a bool).

From the documentation (which is always a good first point of call if something isn't working how you expect):

Return Value true if the specified text range should be replaced; otherwise, false to keep the old text.

Discussion The text field calls this method whenever user actions cause its text to change. Use this method to validate text as it is typed by the user. For example, you could use this method to prevent the user from entering anything but numerical values.

EDIT: (as pointed out by Duncan C in the comments, and as should have been in the original answer) A good starting point is just to return true from this method, as then all the user input will be reflected in the text field. If you need to be more specific about what edits you allow you can introduce that logic later.

flanker
  • 3,840
  • 1
  • 12
  • 20