From 6c21866d3903a99c4e448be811df9f2c9277a077 Mon Sep 17 00:00:00 2001 From: "pengfei.zhou" Date: Sat, 9 May 2020 16:21:43 +0800 Subject: [PATCH] iOS:fix when input hans limit length error --- doric-iOS/Pod/Classes/Shader/DoricInputNode.m | 29 +++++++++++++++++-- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/doric-iOS/Pod/Classes/Shader/DoricInputNode.m b/doric-iOS/Pod/Classes/Shader/DoricInputNode.m index 75954e76..73a3dea2 100644 --- a/doric-iOS/Pod/Classes/Shader/DoricInputNode.m +++ b/doric-iOS/Pod/Classes/Shader/DoricInputNode.m @@ -198,9 +198,10 @@ - (BOOL)textViewShouldEndEditing:(UITextView *)textView { - (void)textViewDidChange:(UITextView *)textView { if (self.maxLength) { - if (textView.text.length > self.maxLength.unsignedIntValue) { - NSRange range = [textView.text rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, self.maxLength.unsignedIntValue)]; - textView.text = [textView.text substringWithRange:range]; + UITextRange *selectedRange = [textView markedTextRange]; + UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0]; + if (!pos) { + textView.text = [self limitToHansMaxLength:self.maxLength.unsignedIntValue text:textView.text]; } } if (self.onTextChange) { @@ -208,4 +209,26 @@ - (void)textViewDidChange:(UITextView *)textView { } [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