iOS:fix when input hans limit length error

This commit is contained in:
pengfei.zhou 2020-05-09 16:21:43 +08:00 committed by osborn
parent 44286bcb28
commit 6c21866d39

View File

@ -198,9 +198,10 @@ - (BOOL)textViewShouldEndEditing:(UITextView *)textView {
- (void)textViewDidChange:(UITextView *)textView { - (void)textViewDidChange:(UITextView *)textView {
if (self.maxLength) { if (self.maxLength) {
if (textView.text.length > self.maxLength.unsignedIntValue) { UITextRange *selectedRange = [textView markedTextRange];
NSRange range = [textView.text rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, self.maxLength.unsignedIntValue)]; UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
textView.text = [textView.text substringWithRange:range]; if (!pos) {
textView.text = [self limitToHansMaxLength:self.maxLength.unsignedIntValue text:textView.text];
} }
} }
if (self.onTextChange) { if (self.onTextChange) {
@ -208,4 +209,26 @@ - (void)textViewDidChange:(UITextView *)textView {
} }
[textView setNeedsLayout]; [textView setNeedsLayout];
} }
- (NSString *)limitToHansMaxLength:(NSUInteger)maxLen text:(NSString *)text{
NSUInteger asciiMaxLen = 2 * maxLen;
__block NSUInteger asciiLen = 0;
__block NSUInteger subStringRangeLen = 0;
[text enumerateSubstringsInRange:NSMakeRange(0, text.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
if ([substring canBeConvertedToEncoding:NSASCIIStringEncoding]) {
asciiLen += 2;
} else {
asciiLen += [substring lengthOfBytesUsingEncoding:NSUTF16StringEncoding];
}
if (asciiLen <= asciiMaxLen) {
subStringRangeLen = substringRange.location + substringRange.length;
} else {
*stop = YES;
}
}];
return [text substringWithRange:NSMakeRange(0, subStringRangeLen)];
}
@end @end