1

I want to show the characters number when I type in a UITextView. But I'm confused when I presse the delete/backspace key.

I use:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

My code is:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSLog(@"input %d chars",textView.text.length + 1);
    return YES;
}

When I type in hello, it shows 'input 5 chars'; But if I click the delete/backspace key, the number become 6, not 4. What's the matter with this? How I can know the exact number of chars in the UITextView when I type in?

John Conde
  • 217,595
  • 99
  • 455
  • 496
Vigor
  • 1,706
  • 3
  • 26
  • 47

4 Answers4

3

You can get the text that is going to be in text field after your edit and then check its length:

NSString* newString = [textField1.text stringByReplacingCharactersInRange:range withString:string];
int newLength = [newString length];
Vladimir
  • 170,431
  • 36
  • 387
  • 313
2

It's pretty obvious :)

You're outputting the length+1

textView.text.length + 1

but a backspace doesn't make the length 1 longer, it makes it 1 shorter!

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

    // Do the replacement
    NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];

   // See what comes out
    NSLog(@"input %d chars", newText.length);

    return YES;
}
deanWombourne
  • 38,189
  • 13
  • 98
  • 110
  • Thank you very much! My method is just bad. I add 1 because I think 1 is the text.length. Now I know how to do it from your answer. – Vigor Sep 11 '12 at 06:07
2

The text view sends textView:shouldChangeTextInRange:replacementText: before it actually changes its text.

It sends textViewDidChange: after it changes its text.

So just implement textViewDidChange: instead:

- (void)textViewDidChange:(UITextView *)textView {
    NSLog(@"textView.text.length = %u", textView.text.length);
}
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
0

Check the length of the replacement text argument, which will be zero in case of a backspace.

There's another case to consider, where the user selects a range of characters and pastes text into the field. In that case, you should also subtract out the length of the replaced text.

NSLog(@"New length is: %d chars",textView.text.length - range.length + text.length);
Husker Jeff
  • 857
  • 1
  • 5
  • 6