美文网首页
UITextView谷歌输入法输入中文时限制字数问题

UITextView谷歌输入法输入中文时限制字数问题

作者: 女山湖小伙子 | 来源:发表于2018-08-14 15:53 被阅读5次

    谷歌输入在输入中文时,输入框中会先显示中文的拼音。例如限制字数为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];
             }
    }
    

    相关文章

      网友评论

          本文标题:UITextView谷歌输入法输入中文时限制字数问题

          本文链接:https://www.haomeiwen.com/subject/ufhtmftx.html