谷歌输入在输入中文时,输入框中会先显示中文的拼音。例如限制字数为5个时,你想输入"我是中国人",当你输入woshiz就会提示字数超限了,下面的代码就是解决这个问题
#define MAXSTRINGLENGTH 15 //限定输入长度
- (void)textViewDidChange:(UITextView *)textView{
NSString *lang = [[[UITextInputMode activeInputModes] firstObject] primaryLanguage];
if ([lang isEqualToString:@"zh-Hans"]){
UITextRange *range = [textView markedTextRange];
UITextPosition *start = range.start;
UITextPosition*end = range.end;
NSInteger selectLength = [textView offsetFromPosition:start toPosition:end];
NSInteger contentLength = textView.text.length - selectLength;
if (contentLength > MAXSTRINGLENGTH){
textView.text = [textView.text substringToIndex:MAXSTRINGLENGTH];
[[[UIAlertView alloc] initWithTitle:@"提示" message:@"最长限制15个字" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil] show];
}
if (contentLength < MAXSTRINGLENGTH){
textCountlabel.text = [NSString stringWithFormat:@"还剩%ld个字", MAXSTRINGLENGTH - contentLength];
}else{
textCountlabel.text = @"还剩0个字";
}}else{
if (textView.text.length > MAXSTRINGLENGTH){
textView.text = [textView.text substringToIndex:MAXSTRINGLENGTH];
[[[UIAlertView alloc] initWithTitle:@"提示" message:@"最长限制15个字" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil] show];
}
textCountlabel.text = [NSString stringWithFormat:@"还剩%ld个字", MAXSTRINGLENGTH-textView.text.length];
}
}