解决textview要求限制最大输入字数时 输入中文、moji

2016-12-30  本文已影响94人  zzchsppy

// 添加通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldEditChanged:)

name:@"UITextViewTextDidChangeNotification" object:self.textv];

// 解决中文  第三方键盘  输入moji表情问题

-(void)textFieldEditChanged:(NSNotification *)obj

{

UITextView *textField = (UITextView *)obj.object;

NSString *toBeString = textField.text;

//获取高亮部分

UITextRange *selectedRange = [textField markedTextRange];

UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];

// 没有高亮选择的字,则对已输入的文字进行字数统计和限制

if (!position)

{

if (toBeString.length > MAXLENGTH)

{

NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:5];

if (rangeIndex.length == 1)

{

textField.text = [toBeString substringToIndex:MAXLENGTH];

}

else

{

NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAXLENGTH)];

textField.text = [toBeString substringWithRange:rangeRange];

}

}

}

}

上一篇下一篇

猜你喜欢

热点阅读