UITextView: characters count is not right when the backspace is typed in
-
01-07-2021 - |
Frage
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?
Lösung
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;
}
Andere Tipps
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];
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);
}
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);