I am trying to implement a character counter for a UITextView, but found the counter inaccurate in the following situation:
- Enter a few characters of text, such as "The"
- Disable refund 25 times
- Hold the delete button to delete the text (and hold it until the cursor reaches the top)
- When the cursor reaches the top (and after deleting "The"), the counter still says that the UITextView contains 3 characters
- Press the delete button again to correctly count the counter and report that there are 0 characters.
I printed the results of the counter and replaceText in this situation, and the last output looks like this:
2009-08-06 15: 29: 14.357 Characters: 3
2009-08-06 15: 29: 14.369
Therefore, it turns out that when a large number of new lines (and possibly large parts of the text in general) are deleted in bulk in this way, textView: shouldChangeTextInRange: replacementText: does not start at the end of this sequence, requiring the addition of a delete button tap.
My counter code is as follows:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { NSString* nextText = [textView.text stringByReplacingCharactersInRange:range withString:text]; int characterCount = [nextText length];
Any ideas on how to overcome this, so the score is correct in this situation (or what can I do wrong)?
source share