美文网首页
组件--限制文本框字数(处理中文拼音占位的影响)

组件--限制文本框字数(处理中文拼音占位的影响)

作者: 要开心 | 来源:发表于2019-04-10 14:44 被阅读0次

    TextView

    -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    {
    //    if ([text isEqualToString:@"\n"]) {
    //        [textView resignFirstResponder];
    //        return NO;
    //    }
        
        NSString *totalText = [NSString stringWithFormat:@"%@%@",textView.text,text];
        UITextRange *rangeSelected = textView.markedTextRange;
        NSInteger validTxtLength = textView.text.length;
        if (rangeSelected) { //在拼音的路上
            NSString *selectedText = [textView textInRange:rangeSelected];
            
            if (![self judgeInputIsChinese:text]) {//还是拼音
                validTxtLength = totalText.length-selectedText.length;
                if (validTxtLength > _maxLength) {
                    NSString *strValid = [textView.text substringWithRange:NSMakeRange(0, textView.text.length-selectedText.length)];
                    NSString *newStr = [strValid stringByAppendingString:text];
                    newStr = [newStr substringWithRange:NSMakeRange(0, _maxLength)];
                    textView.text = newStr;
                    return NO;
                }else{
                    return YES;
                }
                
            }else{//拼完输入汉字了!=
                NSString *strValid = [textView.text substringWithRange:NSMakeRange(0, textView.text.length-selectedText.length)];
                NSString *newStr = [strValid stringByAppendingString:text];
                if (newStr.length>_maxLength) {
                    newStr = [newStr substringWithRange:NSMakeRange(0, _maxLength)];
                }
                textView.text = newStr;
                return NO;
            }
        }
        
        if (totalText.length > _maxLength && text.length>0){//字段长度超过限制,且本步操作不是删除
            textView.text = [totalText substringToIndex:_maxLength];
            return NO;
        }
        
        if (![totalText isEqualToString:@""]) {
            _txvPlaceholder.hidden = YES;
        }
        
        //删除最后一个字符时
        if ([text isEqualToString:@""] && range.location == 0 && range.length == 1) {
            _txvPlaceholder.hidden = NO;
        }
        
        return YES;
    }
    
    //判断是否是全中文字符串
    - (BOOL)judgeInputIsChinese:(NSString *)textStr{
        NSString *regex = @"[\u4e00-\u9fa5]+";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        BOOL isMatch = [pred evaluateWithObject:textStr];
        return isMatch;
        
    }
    

    参考文章:

    1. iOS ...如何使uitextfield不把输入的拼音认作文本编辑框的内容
    2. 正则判断字符串类型

    相关文章

      网友评论

          本文标题:组件--限制文本框字数(处理中文拼音占位的影响)

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