Home > Net >  how to remove character when backspace is pressed swift
how to remove character when backspace is pressed swift

Time:04-05

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

CodePudding user response:

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.

CodePudding user response:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            
            // Backspace handled
            guard !string.isEmpty else {
                return true
            }
            
            return true
        }
  • Related