I have written an article titled how to better limit the input length of a uitextfield. The final conclusion of this article is that it can be directly used.
UIKIT_EXTERN NSString *const UITextFieldTextDidChangeNotification;
Listen to and cut out the parts that exceed maxlength.
So when I was dealing with the content length of uitextview, I also directly referred to this method:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:nil];
- (void)textViewDidChange:(NSNotification *)notification{ self.placeholder.hidden = (self.textView.text.length > 0); if (self.textLengthLimit > 0 && self.textView.text.length > self.textLengthLimit) { self.textView.text = [self.text substringToIndex:self.textLengthLimit]; }}
After this process, I typed several characters on the keyboard, and no more characters were entered when it reached 200 characters. However, when I copy a lot of Chinese content (more than 200 words) from the web page, paste it into uitextview, and then try to input it, it will go down:
*** -[NSConcreteTextStorage attributesAtIndex:effectiveRange:]: Range or index out of bounds
My solution is:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ if (textView.text.length >= self.textLengthLimit && text.length > range.length) { return NO; } return YES;}In this way, when the length reaches 200, the input will no longer respond to changes.
However, after the paste is up to 200 characters, you can unbind the text and then use the Chinese Input Method for input. At this time, entering the multistage text input mode (refer to here) will trigger another problem:
*** Terminating app due to uncaught exception ‘NSRangeException‘, reason: ‘NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds‘
Due to the Lenovo and recommendation functions on the keyboard of the Chinese Input Method, the length of the text content may not meet the expectations, resulting in a cross-border. Therefore, you can refer to this answer for further processing:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ if (textView.text.length >= self.textLengthLimit && text.length > range.length) { return NO; } return YES;}- (void)textViewDidChange:(UITextView *)textView{ self.placeholder.hidden = (self.textView.text.length > 0); if (textView.markedTextRange == nil && self.textLengthLimit > 0 && self.text.length > self.textLengthLimit) { textView.text = [textView.text substringToIndex:self.textLengthLimit]; }}