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?
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;
}