Search code examples
iosswiftuitextview

iOS Backspace not working in UITextView after limiting characters


I want to limit the number of characters the user is allowed to enter in the UITextView. For that I use the delegate method shouldChangeTextInRange.

The problem I have now is how to detect the backspace escape. The works fine but for the backspace doesn't.

How can I detect the backspace?

Any ideas please?

Here is my code

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    {
        if textField == biofield
        {
            if biofield.text == ""
            {
                self.countLbl.text = "0/40"
            }
            else
            {
                let count = self.biofield.text!.count + string.count
                print("Count is ", count)
                self.countLbl.text = "\(count)/40"
            }
            let maxLength = 40          // Set your need
            let currentString: NSString = biofield.text! as NSString
            let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
            return newString.length <= maxLength
            //return false
        }
        else
        {
            return true
        }
    }

Thanks a lot!


Solution

  • I had ever met this problem. and this code worked for me.

    let maxCharacters = 10
    // Check if the user is attempting to delete a character
    if text.count == 0 && textView.text.count > 0 {
        // Allow the backspace key to delete characters
        return true
    }
    
    // Check if the new text will exceed the maximum number of characters
    let textCurrent = textView.text as NSString
    let textNew = textCurrent.replacingCharacters(in: range, with: text)
    return textNew.count <= maxCharacters
    

    Please check this code in shouldChangeTextIn function and let me know.