Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading