iosiphoneuitextviewuitextviewdelegate

Limit number of characters in uitextview


I am giving a text view to tweet some string .

I am applying the following method to restrict the number of characters to 140 in length.

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
   return [[textView text] length] <= 140;
}

The code is working nicely except the first condition that backspace is not working. suppose that I have reached the limit of 140 characters so that the method will give me false and the user can not insert more characters but after that when I try to delete some characters the text view behave as it is disabled .

So the question is: "How to delete characters from textview.text or re-enable the text view?"


Solution

  • You should be looking for an empty string instead, as the apple reference says

    If the user presses the Delete key, the length of the range is 1 and an empty string object replaces that single character.

    I think the check you actually want to make is something like [[textView text] length] - range.length + text.length > 140, to account for cut/paste operations.